Is the not operator (!) behaving differently in TypeScript?

623 Views Asked by At

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?

3

There are 3 best solutions below

5
Titian Cernicova-Dragomir On BEST ANSWER

One of the design goals of Typescript is:

Preserve runtime behavior of all JavaScript code.

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

0
jcalz 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!

Playground link to code

0
Gopinath On

TypeScript is a superset of JavaScript.

Typescript only adds additional features to JavaScript. It does not negate any feature or functionality of JavaScript.

What is false in JavaScript is false in TypeScript also. What is true in JavaScript is also true in TypeScript.