明确检查对象未定义后,对象可能为“未定义”

时间:2021-07-01 14:17:13

标签: typescript

我在使用以下代码时遇到了一些问题:

const sentences: Record<string, string|undefined> = {
    // Empty here but receives properties eventually
};    

const reader = (id: string) => {
    if (sentences.a !== undefined) {
        sentences.a.split(' '); // Works
    }

    if (sentences[id] !== undefined) {
        sentences[id].split(' '); // Object possibly undefined
    }
}

我知道我可以使用 sentences[id]! 但我更想知道为什么第二个分支会以这种方式运行,以及是否有办法让它在不过度使用 ! 的情况下像第一个一样运行

Playground link

2 个答案:

答案 0 :(得分:3)

TypeScript 不会缩小动态访问的属性的范围。但是你可以做的是将值存储到一个变量中,然后它会变窄:

const sentence = sentences[id];
if (sentence !== undefined) {
    sentence.split(' ');
}

Playground link

答案 1 :(得分:1)

要对此进行解释,您可以轻松地执行以下操作:

if (sentences[id] !== undefined) {
    id = "newId"; // <--- mutate id 
    sentences[id].split(' '); 
    // ^^^ This is a problem now. sentences[id] can be undefined
}