[英]Typescript setState with computed property names
I am using Typescript 2.1. 我正在使用Typescript 2.1。 I have a React component with state with 2 collections of numbers, I don't want to duplicate the addItem and removeItem methods and want them to be generic.
我有一个带有2个数字集合的状态的React组件,我不想复制addItem和removeItem方法,并希望它们是通用的。 This is the code:
这是代码:
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)
});
}
...
}
and this is how I call the methods: 这就是我调用方法的方式:
this.addItem('disciplines', id)
Right now in addItem method I get compilation error: 现在在addItem方法中我得到编译错误:
Argument of type '{ [x: string]: number[];
类型'{[x:string]:number []的参数; }' is not assignable to parameter of type 'Pick< State, "lang" |
}'不能赋值给'Pick <State,'lang“|类型的参数 "disciplines" |
“纪律”| "challenges">'.
“挑战”>”。
Property 'lang' is missing in type '{ [x: string]: number[];
类型'{[x:string]:number []中缺少属性'lang'; }'.
}”。
Is there a way to properly type this? 有没有办法正确输入这个? Thanks!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.