我对以下代码有一些问题:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用,sentences[id]!但我更好奇为什么第二个分支会以这种方式运行,以及是否有办法让它像第一个分支一样运行而不会过度使用!
TypeScript 不会缩小动态访问属性的范围。但你可以做的是将值存储到一个变量中,然后它就会缩小:
const sentence = sentences[id];
if (sentence !== undefined) {
sentence.split(' ');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
704 次 |
| 最近记录: |