我正在使用 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< State, "lang" | 的参数 “学科” | “挑战”>'。
类型 '{ [x: string]: number[]; 中缺少属性 'lang' }'。
有没有办法正确输入这个?谢谢!