我正在使用启用了严格的null检查的Typescript。当我尝试编译以下代码时,出现错误“类型'null'不能用作索引类型”。
function buildInverseMap(source: Array<string | null>) {
var inverseMap: { [key: string]: number } = {};
for (let i = 0; i < source.length; i++) {
inverseMap[source[i]] = i;
}
}
显然,inverseMap不能将null作为键,因为类型约束不允许使用它。但是,如果我将inverseMap的类型更改为此:
var inverseMap: { [key: string | null]: number } = {};
我收到错误消息“索引签名参数类型必须为'字符串'或'数字'。” 这很奇怪,因为在Javascript中使用null作为索引是合法的。例如,如果您在浏览器中运行以下代码:
var map = {};
map[null] = 3;
map[null];
输出为3。有没有办法使这种情况在Typescript中发生,或者Typescript不够聪明才能做到这一点?
不管您相信与否,JavaScript中的对象键始终是字符串(可以,或Symbol
s)。(另请参阅此答案)。当您将非字符串值作为键传递时,它将首先被强制为字符串。所以,在
var map = {};
map[null] = 3;
map[null];
您实际上正在设置map["null"]
。观察:
console.log(map["null"]===map[null]); // true
因此,他们在TypeScript中积极决定仅允许string
ornumber
类型作为索引签名。可能是因为大多数时候,任何人尝试使用类似null
方法索引到对象中都表示错误。
就您而言,您可以执行以下操作:
function buildInverseMap(source: Array<string | null>) : {[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]
到string
自己,这让打字稿高兴。如果您记得在String()
每次可能将其与null一起使用时都将其包装在一起,那么它应该对您有用:
const inverseMap = buildInverseMap(['a', 'b', null, 'c']);
const aIndex = inverseMap['a'];
const nullIndex = inverseMap[String(null)];
希望有帮助!祝好运。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句