[英]Why does typescript throw an error on an number | undefined comparison, even after using optional chaining?
Below is the code block that I have where typescript will throw an error on the second if saying that Object may be undefined, in that case, shouldn't typescript just assume that as false when a is undefined
and not throw an error?下面是我的代码块,如果说 Object 可能是未定义的,那么 typescript 将在第二个抛出错误,在这种情况下,不应该 typescript 只是假设
a is undefined
错误时抛出错误?
const condition = true; // can be a condition that could be either true or false
const a: Array<number> | undefined;
if(condition) {
a = [1,2,3,4,5];
}
if(a?.length > 0){
// Have some code
}
Here is a link to the code block and the error being thrown.这是指向代码块和引发错误的链接。 https://www.typescriptlang.org/play?#code/MYewdgzgLgBKYBMCWUngFwCMQgDYFMBDMGAXhigCcBXfAbgFgAoA2Q9GAQUssIE8APGGoBbTPkoA+GAB8Y1RPgBmSMPgSMmSJQAp4yVOACUMAN7MYMQmRgBtAIwAaAEyOAzI4AsAXU0BfZmZtHUIAfgA6AjAAcygACxhpAAYTcyZLAHoMmAAJQgA3fBgIEBEi0AR8Zj8gA
https://www.typescriptlang.org/play?#code/MYewdgzgLgBKYBMCWUngFwCMQgDYFMBDMGAXhigCcBXfAbgFgAoA2Q9GAQUssIE8APGGoBbTPkoA+GAB8Y1RPgBmSMPgSMmSJQAp4yVOACUMAN7MYMQmRgBtAIwAaAEyOAzI4AsAXU0BfZmZtHUIAfgA6AjAAcygACxhpAAYTcyZLAHoMmAAJQgA3fBgIEBEi0AR8Zj8gA
Or is that we are trying to do an undefined > 0
undefined comparison to a number, that is the reason it throws an error?或者我们正在尝试对一个数字进行
undefined > 0
undefined 比较,这就是它引发错误的原因?
Or is that we are trying to do an undefined > 0 undefined comparison to a number, that is the reason it throws an error?
或者我们正在尝试对一个数字进行 undefined > 0 undefined 比较,这就是它引发错误的原因?
That's exactly it.就是这样。 For another example that results in the exact same error, see:
有关导致完全相同错误的另一个示例,请参见:
const undef = void 0;
if (undef > 0) {
// Have some code
}
Nothing to do with your Array<number> | undefined
与您的
Array<number> | undefined
无关Array<number> | undefined
in particular or the optional chaining - it's that TypeScript won't let you compare something that might not be defined against a number, because the comparison doesn't make much sense.特别是
Array<number> | undefined
或可选链接 - 这是 TypeScript 不会让您将可能未定义的内容与数字进行比较,因为比较没有多大意义。 In such a case, where the array isn't defined, would you expect在这种情况下,如果未定义数组,您会期望
if (a?.length > 0) {
to be fulfilled, or not?实现还是不实现? Or are you not entirely sure?
或者你不完全确定? If you're unsure, as many people probably would be without first running the code to see what it results in, that's the point behind this TypeScript error - the code is confusing, so TS is prompting you to fix it.
如果您不确定,因为许多人可能不会先运行代码来查看它的结果,这就是 TypeScript 错误背后的要点 - 代码令人困惑,因此 TS 提示您修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.