The following values are considered "falsy" in JavaScript:
- false
- 0
- ''
- ""
- null
- undefined
- NaN
Does TypeScript handle the not operator (!) differently or is it the same?
The following values are considered "falsy" in JavaScript:
Does TypeScript handle the not operator (!) differently or is it the same?
On
The emitted JavaScript will, by definition, work the same as JavaScript.
As for what types the compiler recognizes as falsy at design time, the short answer is "everything except NaN":
const f0 = !false // true
const f1 = !0; // true
const f2 = !0n; // true
const f3 = !""; // true
const f4 = !null; // true
const f5 = !undefined; // true
const f6 = !NaN; // boolean (no NaN type in TypeScript)
Right now TypeScript doesn't have a numeric literal type corresponding to NaN; it's only seen as type number. And since a number can be either truthy or falsy, the type of !NaN is just boolean. There is an open suggestion, microsoft/TypeScript#28682 to introduce numeric literals for NaN (and for Infinity and -Infinity) but I don't know if that will ever be addressed.
Okay, hope that helps; good luck!
One of the design goals of Typescript is:
This means that ALL Javascript code will behave the same in Typescript code. No exceptions. You might get extra semantic errors, but if you ignore those the behavior is still the same.
So if you ever wonder if an operator such as
!behaves differently in TS, the answer will always be no