这似乎是一个非常简单的打字稿片段:
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)
但我想了解为什么编译器不尊重显式未定义检查。
答案 0 :(得分:2)
Typescript 显示此错误是因为您没有正确检查变量是否未定义。您似乎在到达块之前定义了它,但它可能无法定义。
这就是为什么你不应该禁用 noUncheckedIndexedAccess
- 在这种情况下 - 它会引入一个错误的地方。
仅供参考 - 添加?在密钥的末尾告诉 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)
因为一个值可能是未定义的,如果检查未定义将有与您预期的结果相反。
这不适用于上面的示例,因为它在检查之前被强制转换为变量,因此它只能是字符串或未定义的 - 它不能包含未定义的值