类属性:在 TypeScript 中"Object is possibly undefined"



这似乎是一个非常简单的类型脚本片段:

class Example {
private items: Record<string, number[]> = {}
example(key: string): void {
if (this.items[key] === undefined) {
this.items[key] = []
}
this.items[key].push(1)
}
}

但它给出了this.items[key].push(1)的以下错误:

Object is possibly 'undefined'.ts(2532)

这项工作:

this.items[key]?.push(1)

但我想理解为什么编译器不尊重显式的未定义检查。

Typescript显示此错误,因为您没有正确检查变量是否未定义。似乎是在到达块之前对其进行了定义,但可能无法对其进行定义。

这就是为什么不应该禁用noUncheckedIndexedAccess——在这种情况下——它会为bug引入一个位置。

仅供参考-添加?在键的末尾告诉ts,你知道键已经定义了,不要检查。如果可能的话,应该避免。

不检查-您原始检查

example(key: string): void {
// this is checking before your push
if (this.items[key] === undefined) {
this.items[key] = []
}
// independent from previous check and still reachable even if the variable is undefined
this.items[key].push(1)
}

检查

example(key: string): void {
const item = this.items[key];
if (!item) {
this.items[key] = [1]
} else {
item.push(1)
}
}

当检查一个键是否存在时,需要注意的一点是,与只检查它是否未定义相比,更可靠的方法是this.items.hasOwnProperty(key)!(key in this.itmes),因为一个值可能是未定义的,如果检查未定义,则会产生与预期相反的结果。

这不适用于上面的例子,因为它在检查之前被强制转换为变量,所以它只能是字符串或未定义的-它不能包含未定义的值

相关内容

最新更新