typescript索引类型_typescript – 类型’null’不能用作索引类型

无论信不信,JavaScript中的对象键始终是

strings(好的,或者是

Symbols). (也见

this answer).当您将非字符串值作为键传递时,它会先被强制转换为字符串.所以,在

var map = {};

map[null] = 3;

map[null];

你实际上是在设置map [“null”].注意:

console.log(map["null"]===map[null]); // true

因此,在TypeScript中,他们主动决定only allow the string or number type as index signatures.可能是因为大多数时候,任何试图使用null之类的东西索引到对象的人都表示错误.

在您的情况下,您可以这样做:

function buildInverseMap(source: Array) : {[key: string] : number} {

var inverseMap: { [key: string]: number } = {};

for (let i = 0; i < source.length; i++) {

inverseMap[String(source[i])] = i; // coerce to string yourself

}

return inverseMap;

}

注意我们如何强制source [i]串起自己,这使得TypeScript感到高兴.如果你记得用String()包装密钥,只要你可以使用null,它应该适合你:

const inverseMap = buildInverseMap(['a', 'b', null, 'c']);

const aIndex = inverseMap['a'];

const nullIndex = inverseMap[String(null)];

希望有所帮助!祝好运.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值