我正在使用 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:字符串]”中缺少属性“lang”:
数字[]; }'。
有没有办法正确输入这个?谢谢!
这似乎是 TypeScript 编译器中的一个错误,所以我们必须等待修复。
跟踪的问题是here https://github.com/Microsoft/TypeScript/issues/13948.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)