繁体   English   中英

Class 属性:TypeScript 中的“对象可能未定义”

[英]Class property: "Object is possibly undefined" in TypeScript

这似乎是一个非常简单的 typescript 片段:

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 - 在这种情况下 - 它会引入一个错误的地方。

仅供参考 - 添加? 在密钥的末尾告诉 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)因为一个值可能是未定义的,如果检查undefined 会产生与您预期相反的结果。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM