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!
this.setState({ [collection]: this.state[collection].filter(anId => anId !== id) } as any);but there must be some better solution