这看起来像是一个非常简单的打字代码片段:
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)但是我想要理解为什么编译器不尊重显式的未定义检查。
发布于 2021-05-18 07:37:38
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),因为一个值可能是未定义的,如果检查未定义的值,将会得到与您预期相反的结果。
这不适用于上面的示例,因为它在检查之前被转换为变量,因此它只能是字符串或未定义的-它不能包含未定义的值
https://stackoverflow.com/questions/67577846
复制相似问题