typescript获取属性名_javascript – 具有计算属性名称的Typescript setState

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

type Collection = 'challenges' | 'disciplines';

type State = {

lang: string;

challenges: number[];

disciplines: number[];

}

class MyComponent extends React.Component {

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方法中我得到编译错误:

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[]; }’.

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

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

跟踪问题是here.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值