简体   繁体   English

Typescript:object可能是比较表达式中报告的null

[英]Typescript: object is possibly null reported in a comparison expression

I'm getting a TS18047 on a comparison where the false result of null comparison is a desired outcome.我得到一个 TS18047 进行比较,其中 null 比较的错误结果是期望的结果。

so, basically:所以,基本上:

const a: number | null = null;
if (a >= 250) { /* will not execute because result of comparison is false */ }

this is what I want.这就是我要的。 and this code also worked before I introduced typescript.这段代码在我介绍 typescript 之前也有效。

I know I could just do a null check, but there's like ten branches comparing this variable against various numbers.我知道我可以做一个 null 检查,但是有大约十个分支将这个变量与各种数字进行比较。

Only the final else processes the actual null value.只有最后的else处理实际的 null 值。

Do I actually have to check for null or is it possible for me to wiggle out of this?我真的需要检查 null 还是我可以摆脱这个?

Well this should technically work because you can't compare something that's null to a number because it will always be false, so you need to null check it first.那么这在技术上应该是可行的,因为你不能将 null 的东西与一个数字进行比较,因为它总是错误的,所以你需要先用 null 检查它。

if (a && a >= 250) {
      // do something

 }

This will also work but it's not best practice because it defeats the purpose of typescript这也可行,但这不是最佳实践,因为它违背了 typescript 的目的

    if (a! >= 250) {
      // do something

 }

The typeof Method has sometimes worked for me. typeof方法有时对我有用。

if (typeof a == 'number' && a >= 250) {
        //do something 
}

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

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