You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
Enums and literal types allow you to represent a fixed set of values in TypeScript. Whilst JavaScript has no native enum construct, TypeScript provides several ways to define and enforce constrained value sets. This lesson covers numeric enums, string enums, const enums, literal types, and the as const assertion.
Numeric enums assign auto-incrementing numbers to each member, starting at 0 by default:
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
const move: Direction = Direction.Up;
console.log(move); // 0
You can set a custom starting value:
enum HttpStatus {
OK = 200,
Created = 201,
BadRequest = 400,
NotFound = 404,
InternalServerError = 500,
}
function isSuccess(status: HttpStatus): boolean {
return status >= 200 && status < 300;
}
Numeric enums support reverse mapping — you can look up the name from the value:
enum Colour {
Red,
Green,
Blue,
}
console.log(Colour.Red); // 0
console.log(Colour[0]); // 'Red'
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.