Close

TypeScript - Const Enums

[Updated: Oct 14, 2018, Created: Oct 14, 2018]

In TypeScript it is possible for enums to avoid cost of extra generated code and additional indirection when accessing enum values.

This is done by using keyword const with enum declaration. Let's understand that with an example.

Example

const enum Align {
    LEFT, CENTER, RIGHT
}

let left = Align.LEFT;
console.log(left);

Output

0

The compiled JavaScript:

let left = 0 /* LEFT */;
console.log(left);

As seen in the compiled JavaScript code above, the const enum definition is completely removed on compilation. Const enum members' values are inlined where they are used. For that reason it won't be possible to do things like looping through enum elements:

const enum Align {
    LEFT, CENTER, RIGHT
}

for (let key in Align) {
    console.log(`key=${key}, value=${Align[key]}`);
}

Output

const-enum-example2.ts(5,17): error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.
const-enum-example2.ts(6,44): error TS2476: A const enum member can only be accessed using a string literal.

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.1
TypeScript - Const Enums Select All Download
  • typescript-const-enums
    • const-enum-example.ts

    See Also