As described in What does "all legal JavaScript is legal TypeScript" mean?, TypeScript may issue type warnings on code that it considers incorrect. JavaScript is very permissive compared to many other languages, and will happily allow you to do things like use the greater-than >
operator to compare two completely unrelated values like undefined
and 0
. The JavaScript specification interprets undefined > 0
as if it were NaN > 0
(using the "not-a-number" NaN
value), and NaN
compares as false
to everything else, no matter what. So undefined > 0
is well-defined in JavaScript. But is it good JavaScript?
That's subjective, but the whole point of TypeScript is that it attempts to overlay a static type system on top of JavaScript. If JavaScript had a stricter type system, it would definitely support x > y
where x
and y
are both number
s, and it also would support it where x
and y
are both string
s. But anything else is probably a mistake. Or at least that's the stance TypeScript takes.
TypeScript will be happy if you refactor that comparison so that you only use >
on two numbers, such as by checking whether a
is truthy first:
if (a && a.length > 0) { }
In the particular case you bring up, where optional chaining means you are possibly comparing undefined
to a number, there is an open feature request to support it in microsoft/TypeScript#45543. It's marked as Awaiting More Feedback, which means the TS team would want to see more demand for it and the reasoning behind it before thinking of implementing it. If you really want to see it happen, you might want to give the issue a , but pragmatically speaking it is unlikely to make much difference.
In that issue it is mentioned that if you want this behavior right now you could use the non-nullish assertion operator !
to pretend that the possibly-undefined
value is not undefined
, and this will suppress the error:
if (a?.length! > 0) {}
So if you really need to use this technique instead of the type safe version, you can do so without waiting for an unlikely change to the language.
Playground link to code