具有计算属性名称的Typescript setState

Max*_*kin 5 javascript typescript reactjs

我正在使用Typescript 2.1。我有一个带有2个数字集合的状态的React组件,我不想复制addItem和removeItem方法,并希望它们是通用的。这是代码:

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)
    });
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

这就是我所谓的方法:

this.addItem('disciplines', id)
Run Code Online (Sandbox Code Playgroud)

现在在addItem方法中,我得到编译错误:

类型'{[x:string]:number []; }'不可分配给'Pick <State,“ lang” | “学科” | “挑战“>”。

类型'{{[x:string]:number [];)中缺少属性'lang'。}'。

有没有办法正确输入?谢谢!

Max*_*kin 3

这似乎是 TypeScript 编译器中的一个错误,所以我们必须等待修复。

追踪的问题就在这里