简体   繁体   English

strictNullCheck打字稿中的可迭代对象

[英]strictNullChecks iterables in typescript

Having following possible issue with strictNullChecks in TypeScript (v. 3.2.1): TypeScript(v。3.2.1)中的strictNullChecks存在以下可能的问题:

interface IData {
    data?: { payload: string };
}
const list: IData[] = [];
const index: number = 0;

//test a
if (list[index].data)
    list[index].data.payload = "a";

//test b
const item = list[index].data;
if (item)
    item.payload = "a";

Why does "test a" leads to a warning "object is possibly undefined" and "test b" not? 为什么“测试a”会导致警告“对象可能未定义”而“测试b”却没有? I there a good reason for the behavior? 我的行为是否有充分的理由?

http://www.typescriptlang.org/play/#src=interface%20IData%20%7B%0D%0A%20%20%20%20data%3A%20%7B%20payload%3A%20string%20%7D%20%7C%20undefined%3B%0D%0A%7D%0D%0Aconst%20list%3A%20IData%5B%5D%20%3D%20%5B%5D%3B%0D%0Aconst%20index%3A%20number%20%3D%200%3B%0D%0A%0D%0A%2F%2Ftest%20a%0D%0Aif%20(list%5Bindex%5D.data)%0D%0A%20%20%20%20list%5Bindex%5D.data.payload%20%3D%20%22a%22%3B%0D%0A%0D%0A%2F%2Ftest%20b%0D%0Aconst%20item%20%3D%20list%5Bindex%5D.data%3B%0D%0Aif%20(item)%0D%0A%20%20%20%20item.payload%20%3D%20%22a%22%3B http://www.typescriptlang.org/play/#src=interface%20IData%20%7B%0D%0A%20%20%20%20data%3A%20%7B%20payload%3A%20string%20%7D %20%7C%20undefined%3B%0D%0A%7D%0D%0Aconst%20list%3A%20IData%5B%5D%20%3D%20%5B%5D%3B%0D%0Aconst%20index%3A%20number %20%3D%200%3B%0D%0A%0D%0A%2F%2Ftest%20a%0D%0Aif%20(list%5Bindex%5D.data)%0D%0A%20%20%20%20list20% 5Bindex%5D.data.payload%20%3D%20%22a%22%3B%0D%0A%0D%0A%2F%2Ftest%20b%0D%0Aconst%20item%20%3D%20list%5Bindex%5D。 data%3B%0D%0Aif%20(item)%0D%0A%20%20%20%20item.payload%20%3D%20%22a%22%3B

The "closest comparable" key difference would be between: “最接近的可比性”关键区别在于:

if (list[0].data)
    list[0].data.payload = "a"; // OK

... and ... ...和...

if (list[index].data)
    list[index].data.payload = "a"; // Possibly NULL!

The answer to the question why is one different to the other is really the amount of analysis you need to perform to get to the answer during compilation. 问题的答案为什么一个与另一个不同,实际上是您在编译期间需要执行的分析量才能得出答案。 There is an interesting post on GitHub about the trade-offs in control flow analysis that helps to explain this. GitHub上有一篇有趣的文章,介绍了控制流分析的权衡取舍 ,有助于解释这一点。

In your case, the use of the variable for the index currently prevents the type guard from sticking. 在您的情况下,当前为index使用变量可以防止类型保护程序停留。 Your solution of an intermediate variable is a pretty pragmatic fix. 您对中间变量的解决方案非常实用。

const item = list[index].data;
if (item)
    item.payload = "a";

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

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