【问题标题】:Typescript setState with computed property names具有计算属性名称的打字稿 setState
【发布时间】:2017-02-07 14:55:03
【问题描述】:

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

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

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

【问题讨论】:

  • 我使用类似这样的方法解决了这个错误:this.setState({ [collection]: this.state[collection].filter(anId =&gt; anId !== id) } as any); 但必须有更好的解决方案
  • @Giladd 我发现这是 TypeScript 编译器中的一个错误,现在正在跟踪问题here

标签: javascript reactjs typescript


【解决方案1】:

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

跟踪的问题是here

【讨论】:

猜你喜欢
  • 2019-04-20
  • 1970-01-01
  • 2010-10-29
  • 2023-01-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2017-11-18
  • 2023-01-23
相关资源
最近更新 更多