这看起来像是一个非常简单的打字代码片段:
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];