简体   繁体   English

当我检查值是否在前一行中定义时,为什么 Typescript 会抱怨可能的未定义值?

[英]Why is Typescript complaining about a possible undefined value when I'm checking if the value is defined in a previous line?

I have this code, I'm wondering why Typescript is complaining, the function isNextWeek expects a string and here the code complains that argument of type string or undefined is not assignable, but aren't I checking for the localTime being defined in the localTimeExists check - so it should never call the function if it's undefined.我有这段代码,我想知道为什么 Typescript 会抱怨,函数 isNextWeek 需要一个字符串,这里的代码抱怨类型 string 或 undefined 的参数不可分配,但我不是在检查 localTimeExists 中定义的 localTime检查 - 所以它不应该在未定义的情况下调用该函数。

Not sure why it's complaining, or if anyone has suggestions to avoid this issue.不知道为什么它会抱怨,或者是否有人有避免这个问题的建议。 I did manage to avoid it by wrapping it in an 'if' condition but then that scopes the value to that block and I want to use it outside so wondered if there is another way.我确实设法通过将它包装在“if”条件中来避免它,但随后将值范围限定为该块,我想在外面使用它,所以想知道是否有另一种方法。 Thanks谢谢

const localTimeExists = !!out && !!out.localTime;
const doThis = !isToday && localTimeExists && isNextWeek(out.localTime);

引用对我有用的@Bergis 评论 - 我通过将真实检查内联来实现这一点,因为在进行推理时将其提取到一个单独的行中混淆了 Typescript。

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

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