无论信不信,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)];
希望有所帮助!祝好运.