8

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!

2
  • I worked around this error using something like this: this.setState({ [collection]: this.state[collection].filter(anId => anId !== id) } as any); but there must be some better solution Commented Mar 9, 2017 at 10:37
  • @Giladd I found that this is a bug in TypeScript compiler and am now tracking the issue here. Commented Mar 9, 2017 at 13:04

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There is a workaround available: github.com/Microsoft/TypeScript/issues/… this.setState({ [key as any]: value });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.