2023-07-04 by Wills


Roughly speaking, once TypeScript’s compiler is done with checking your code, it erases the types to produce the resulting “compiled” code.

Here is a basic example where void type is erased.

// src/basic.ts

function cuckoo(): void { // <-- void is removed
  console.log("cuckoo");
}
// src/basic.js

function cuckoo() {
  console.log("cuckoo");
}

There is a nuance in the words “Roughly speaking”. Many (including myself) thought that everything from TypeScript (TS) are erased. This is not true, some syntaxes are instead converted to something JavaScript (JS) recognizes.

It’s worth noting that depending on TS and JS versions what remains will be different. More on this later.

Enum

Enums are real objects that exists at runtime.

Enums are the most obvious remnants of TS.

// src/enum.ts

enum Direction {
  Up,
  Down,
  Left,
  Right,
}

const directions = [
  Direction.Up,
  Direction.Down,
  Direction.Left,
  Direction.Right,
];
// src/enum.js

var Direction;
(function (Direction) {
    Direction[Direction["Up"] = 0] = "Up";
    Direction[Direction["Down"] = 1] = "Down";
    Direction[Direction["Left"] = 2] = "Left";
    Direction[Direction["Right"] = 3] = "Right";
})(Direction || (Direction = {}));
var directions = [
    Direction.Up,
    Direction.Down,
    Direction.Left,
    Direction.Right,
];

Notice that enum Direction is compiled into JS object Direction and not erased away.

Aside 1: Since Enums are just objects, you can pass enums as values.