Typescript setState with computed property names

落爺英雄遲暮 提交于 2021-02-18 22:32:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!