Max*_*kin 5 javascript typescript reactjs
我正在使用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)
});
}
...
}
Run Code Online (Sandbox Code Playgroud)
这就是我所谓的方法:
this.addItem('disciplines', id)
Run Code Online (Sandbox Code Playgroud)
现在在addItem方法中,我得到编译错误:
类型'{[x:string]:number []; }'不可分配给'Pick <State,“ lang” | “学科” | “挑战“>”。
类型'{{[x:string]:number [];)中缺少属性'lang'。}'。
有没有办法正确输入?谢谢!
| 归档时间: |
|
| 查看次数: |
1536 次 |
| 最近记录: |