Reputation: 779
let myVar: number | undefined;
if (100 > myVar) doSomething();
Typescript tells me "myVar" is possibly undefined. What's wrong with that? I know it is, I explicitly typed it as such, but it seemingly doesn't want me to put it in the comparison? I know the outcome of the comparison if the variable is undefined, in fact I'm depending on that behaviour, what does Typescript want me to do?
Upvotes: 1
Views: 172
Reputation: 141512
Why is typescript upset about comparing to undefined?
If strictNullChecks
is enabled, TypeScript will enforce greater type safety. As of early 2017, that increased type safety means it is an error if "either operand of a <
, >
, <=
, >=
, or in
operator is nullable
."
what does Typescript want me to do?
When a type is a union of number | undefined
, TypeScript wants you to check for undefined
before running a relational operator.
let doSomething = () => undefined;
let myVar: number | undefined;
if (myVar && 100 > myVar) doSomething();
In the case of zero being a valid falsy value, you can use one of these forms:
if ((myVar || 0) && 100 > myVar) doSomething();
if (myVar !== undefined && 100 > myVar) doSomething();
Upvotes: 1
Reputation: 220964
You've set up a trap for the next person to edit this code, who might think that writing
if (myVar >= 100) {
// Handle the other case
} else {
doSomething();
}
is a valid way to refactor the code.
You could write if (100 > myVar!)
if you wanted to pretend that myVar
was never undefined
, though that probably communicates an even more dangerous intent.
if (100 > (myVar || 0))
might be a clearer way that communicates that undefined
and 0
get the same treatment in this particular case.
Upvotes: 2