Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript setState with computed property names

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!

like image 830
Max Semikin Avatar asked Feb 07 '17 14:02

Max Semikin


1 Answers

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.

like image 177
Max Semikin Avatar answered Oct 15 '22 10:10

Max Semikin