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