带有计算属性名称的 Typescript setState

IT技术 javascript reactjs typescript
2021-05-17 18:30:07

我正在使用 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< State, "lang" | 的参数 “学科” | “挑战”>'。

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

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

1个回答

这似乎是 TypeScript 编译器中的一个错误,因此我们将不得不等待修复。

跟踪问题在这里