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'
String enums require an explicit string value for each member. They do not support reverse mapping, but are far more readable in logs and debugging:
enum LogLevel {
Debug = 'DEBUG',
Info = 'INFO',
Warn = 'WARN',
Error = 'ERROR',
}
function log(level: LogLevel, message: string): void {
console.log(`[${level}] ${message}`);
}
log(LogLevel.Info, 'Server started');
// [INFO] Server started
String enums are generally preferred in modern TypeScript because they are more predictable and produce clearer output.
Const enums are completely inlined at compile time — they produce no JavaScript output:
const enum Size {
Small = 'S',
Medium = 'M',
Large = 'L',
}
const shirtSize = Size.Medium;
// Compiled JS: const shirtSize = "M";
Const enums are excellent for performance-sensitive code, but they have limitations:
Object.keys() or Object.values()TypeScript allows you to use specific values as types. These are called literal types:
// String literal types
type Theme = 'light' | 'dark' | 'system';
function setTheme(theme: Theme): void {
console.log(`Setting theme to: ${theme}`);
}
setTheme('dark'); // OK
// setTheme('blue'); // Error: Argument of type '"blue"' is not assignable
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.