问题
I am using 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. 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:
Argument of type '{ [x: string]: number[]; }' is not assignable to parameter of type 'Pick< State, "lang" | "disciplines" | "challenges">'.
Property 'lang' is missing in type '{ [x: string]: number[]; }'.
Is there a way to properly type this? Thanks!
回答1:
It seems to be a bug in the TypeScript compiler, so we will have to wait for the fix.
The issue for tracking is here.
来源:https://stackoverflow.com/questions/42092978/typescript-setstate-with-computed-property-names