In JavaScript, null operands in a relational expression are treated as 0:
function f() { return /* either a number or null */; }
let b = f() < 0; // false if f() returns null
But in TypeScript, if I provide a type annotation for f
and turn on strict null checking, then I get the compiler error Object is possibly 'null'
:
function f(): number | null { return /* either a number or null */; }
let b = f() < 0; // <-- error TS2531
Is there a way to tell the compiler that nullable operands are acceptable here?
I can shut the compiler up with a non-null assertion on f()
, but I worry that f()!
could mislead code reviewers because f()
can return null here.