Home > Software engineering >  Typescript: object is possibly null reported in a comparison expression
Typescript: object is possibly null reported in a comparison expression

Time:01-11

I'm getting a TS18047 on a comparison where the false result of null comparison is a desired outcome.

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.

I know I could just do a null check, but there's like ten branches comparing this variable against various numbers.

Only the final else processes the actual null value.

Do I actually have to check for null or is it possible for me to wiggle out of this?

CodePudding user response:

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.

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

 }

This will also work but it's not best practice because it defeats the purpose of typescript

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

 }

CodePudding user response:

The typeof Method has sometimes worked for me.

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