具有计算属性名称的Typescript setState

时间:2017-02-07 14:55:04

标签: javascript reactjs typescript

我正在使用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)
    });
  }

  ...

}

这就是我调用方法的方法:

this.addItem('disciplines', id)

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

  

类型'{[x:string]:number []的参数; }'不可分配给   'Pick&lt;类型的参数国家,“郎”| “学科”   | “挑战” &GT;”

     

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

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

1 个答案:

答案 0 :(得分:3)

它似乎是TypeScript编译器中的一个错误,因此我们必须等待修复。

跟踪问题是here