Skip to content

Instantly share code, notes, and snippets.

@vdeturckheim
Last active March 16, 2021 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdeturckheim/4bbb6c32b8528ecdff9ee98b21fb7932 to your computer and use it in GitHub Desktop.
Save vdeturckheim/4bbb6c32b8528ecdff9ee98b21fb7932 to your computer and use it in GitHub Desktop.

Typescript is not really a superset of JavaScript

Let's consider T(ts: string): string, the function compiling TypeScript code to JavaScript. If TypeScript is a superset of JavaScript, then, for all valid Javascript expression js, T(js) === js as the compiler should consider valide JavaScript expression as valid TypeScript expression that do not need to be changed during compilation (of course, we consider that the JavaScript version of the input of T is the same as the output one).

In order to demonstrate that TypeScript is not a superset of JavaScript, one only need to find a single JavaScript expression jsbreak as of T(jsbreak) !== jsbreak.

Let's consider the expression

// in a .ts file
Map<String, String>([])

which compiles to

"use strict";
Map([]);

(according to https://www.typescriptlang.org/play?ssl=1&ssc=24&pln=1&pc=1#code/LIQwDgPAygLgTgSwHYHMA0ACWjUD4AUA2gLoCUAUEA)

Now, let's evaluate the same expression in JavaScript (in the Node.js REPL)

Map<String, String>([])

this evaluates to true.

In this situation, a valid piece of JavaScript is actually compiled into an invalid one (as the Map constructor must be called with new) by the TypeScript compiler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment