【发布时间】:2017-02-07 14:55:03
【问题描述】:
我正在使用 Typescript 2.1。我有一个带有 2 个数字集合的状态的 React 组件,我不想复制 addItem 和 removeItem 方法并希望它们是通用的。这是代码:
type Collection = 'challenges' | 'disciplines';
type State = {
lang: string;
challenges: number[];
disciplines: number[];
}
class MyComponent extends React.Component<{}, State> {
addItem = (collection: Collection, id: number) => {
this.setState({
[collection]: [...this.state[collection], id],
});
}
removeItem = (collection: Collection, id: number) => {
this.setState({
[collection]: this.state[collection].filter(anId => anId !== id)
});
}
...
}
这就是我调用方法的方式:
this.addItem('disciplines', id)
现在在 addItem 方法中我得到编译错误:
类型参数 '{ [x: string]: number[]; }' 不可分配给 'Pick
类型 '{ [x: string] 中缺少属性 'lang': 数字[]; }'。
有没有办法正确输入?谢谢!
【问题讨论】:
-
我使用类似这样的方法解决了这个错误:
this.setState({ [collection]: this.state[collection].filter(anId => anId !== id) } as any);但必须有更好的解决方案 -
@Giladd 我发现这是 TypeScript 编译器中的一个错误,现在正在跟踪问题here。
标签: javascript reactjs typescript