Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile an enum in TypeScript

Tags:

typescript

What do enums become at runtime in TypeScript?

Fruit.ts

enum Fruit {APPLE, ORANGE};

main.ts

var bowl = [Fruit.APPLE, Fruit.ORANGE];
console.log(bowl);

The generated main.js file just stays the same as the .ts, however that won't work.

like image 490
ᅙᄉᅙ Avatar asked Sep 30 '15 16:09

ᅙᄉᅙ


1 Answers

The JS for that code will be:

// Fruit.js
var Fruit;
(function (Fruit) {
    Fruit[Fruit["APPLE"] = 0] = "APPLE";
    Fruit[Fruit["ORANGE"] = 1] = "ORANGE";
})(Fruit || (Fruit = {}));

// main.js
var bowl = [Fruit.APPLE, Fruit.ORANGE];
console.log(bowl);

You're probably looking for a const enum though:

const enum Fruit {APPLE, ORANGE};

If you use that, then the values of the enum will be inlined to the JavaScript:

// Fruit.js: empty.. nothing will be in here

// main.js
var bowl = [0 /* APPLE */, 1 /* ORANGE */];
console.log(bowl);

You can use a const enum when the JS code that a regular enum generates isn't necessary in your application.

like image 131
David Sherret Avatar answered Nov 07 '22 04:11

David Sherret