0
0
Typescriptprogramming~5 mins

Const enums and optimization in Typescript

Choose your learning style9 modes available
Introduction

Const enums help make your code faster and smaller by replacing enum values directly in the code.

When you want to use fixed named values without extra code at runtime.
When you want your program to run faster by avoiding extra lookups.
When you want to reduce the size of your compiled JavaScript file.
When you have simple sets of related constants like directions or colors.
Syntax
Typescript
const enum EnumName {
  VALUE1,
  VALUE2 = 5,
  VALUE3
}

Const enums are declared with the const enum keywords.

The compiler replaces enum uses with their actual values, so no enum object exists at runtime.

Examples
This enum has default values starting from 0. Using Direction.Up will be replaced by 0 in the compiled code.
Typescript
const enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move = Direction.Up;
Here, values are set manually. Status.Success will be replaced by 1 in the output.
Typescript
const enum Status {
  Success = 1,
  Failure = 0
}

let result = Status.Success;
Sample Program

This program uses a const enum Colors. When compiled, Colors.Green is replaced by 1 directly, so the output is the number 1.

Typescript
const enum Colors {
  Red,
  Green,
  Blue
}

function printColor(color: Colors) {
  console.log(color);
}

printColor(Colors.Green);
OutputSuccess
Important Notes

Const enums cannot be used with computed members.

They are removed during compilation, so you cannot get their keys or values at runtime.

Use const enums only when you do not need the enum object at runtime.

Summary

Const enums replace enum references with actual values to optimize code.

They reduce runtime code size and improve speed.

Use them for fixed sets of constants when you don't need enum objects at runtime.