Typescript is complaining about an expression of this form:
if (foo?.length > 3) {
saying that foo
is possible undefined (ts18048) , which is true. But if it's true, then foo?.length
will evaluate to undefined
, which will not be greater than 3, which is the behaviour I want.
Is there an idiomatic way to reassure TypeScript?
I can do if (foo && foo.length > 3)
but in this case, foo
is quite a long expression.
Idiomatic TypeScript would indeed be to test for null
explicitly:
if (foo != null && foo.length > 3)
If foo
is a longer expression, declare a new variable for it, which you probably also will reuse inside of the if
block anyway.
However, if that really doesn't suit your needs, you can use nullish coalescing to get a value that TypeScript accepts for the numeric comparison:
if (foo?.length ?? 0 > 3)
For the length of an array, 0
seems to be a sensible default, for anything else you can also use +Infinity
or -Infinity
.