类型'null'不能用作索引类型

亚伦

我正在使用启用了严格的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中的对象键始终是字符串(可以,或Symbols)。(另请参阅此答案)。当您将非字符串值作为键传递时,它将首先被强制为字符串。所以,在

var map = {};
map[null] = 3;
map[null];

您实际上正在设置map["null"]观察:

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

因此,他们在TypeScript中积极决定仅允许stringornumber类型作为索引签名可能是因为大多数时候,任何人尝试使用类似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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

类型“{}”不能用作索引类型

类型“X”不能用作索引类型

类型不能用作索引类型

类型'undefined'不能用作索引类型

打字稿错误-类型'string []'不能用作索引类型

类型 '() => Promise<AxiosResponse<any>>' 不能用作索引类型 [ReactJs]

类型“未定义”不能用作索引类型

类型 'any[]' 不能用作索引类型 Angular 构建

Typescript:类型'undefined'不能用作索引类型.ts(2538)

类型'<null>'的值不能用作默认参数,因为没有标准转换为类型'T'

错误 TS2538:类型“CCCustomer”不能用作索引类型

为什么我在TypeScript中遇到“类型'String'不能用作索引类型”错误

响应 yup 错误类型“未定义”不能用作索引类型。TS2538

介质不能用作请求的设备类型

TS2536:即使类型必须是键,也不能用作索引?

打字稿:从嵌套的全局对象访问值 | 键入“字符串”不能用作索引类型

Entity Framework Core:表“Users”中的“Id”列的类型不能用作索引中的键列

包的类型不能用作供应商的包的类型

F#-类型参数不能用作类型构造函数

类型“键”不能用于索引 TypeScript 中的类型“对象”

类型“ N [P]”不能用于索引类型“ IComponents <N>”

类型'string'不能用于索引类型'T'.ts(2536)

类型“ test”不能用于索引类型“ T”

类型 'string' 不能用于索引类型 'Partial<T>

Golang不能用作类型struct数组或slice文字

为什么“ kotlin.Result”不能用作返回类型?

TypeScript 联合类型不能用作数组

类型X不能用作通用类型Y中的类型参数T

类型“ T”不能用作通用类型或方法中的类型参数“ T”