08-enums.ts
Typescript/src/01-beginner/08-enums.ts
// ============================================
// 08. Enums
// ============================================
// Numeric Enums - default behavior
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
let direction: Direction = Direction.Up;
console.log(direction); // 0
// Custom Numeric Values
enum Status {
Pending = 1,
Approved = 2,
Rejected = 3
}
// Or start from a specific number
enum Status2 {
Pending = 100,
Approved, // 101
Rejected // 102
}
// String Enums
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}
let color: Color = Color.Red;
console.log(color); // "red"
// Heterogeneous Enums (not recommended)
enum Mixed {
No = 0,
Yes = "yes"
}
// Computed and Constant Members
enum FileAccess {
None, // 0 (constant)
Read = 1 << 1, // 2 (computed)
Write = 1 << 2, // 4 (computed)
ReadWrite = Read | Write // 6 (computed)
}
// const Enums - inlined at compile time
const enum DirectionConst {
Up,
Down,
Left,
Right
}
let directionConst = DirectionConst.Up;
// Compiles to: let directionConst = 0;
// Reverse Mapping (numeric enums only)
enum DirectionReverse {
Up = 1,
Down,
Left,
Right
}
console.log(DirectionReverse.Up); // 1
console.log(DirectionReverse[1]); // "Up" (reverse mapping)
// String enums don't have reverse mapping
// Color["red"]; // undefined
// Common Use Cases
// HTTP Status Codes
enum HttpStatus {
OK = 200,
NotFound = 404,
ServerError = 500
}
// API Response Codes
enum ApiResponse {
Success = "SUCCESS",
Error = "ERROR",
Pending = "PENDING"
}
// Flags/Bitwise operations
enum Permission {
Read = 1,
Write = 2,
Execute = 4
}
const userPermissions = Permission.Read | Permission.Write;
console.log(userPermissions & Permission.Read); // 1 (has read permission)
export { Direction, Status, Color, HttpStatus, ApiResponse, Permission };
관련 글
01-introduction.ts
01-introduction.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/01-introduction.ts).
글 읽기 →02-basic-types.ts
02-basic-types.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/02-basic-types.ts).
글 읽기 →03-variables.ts
03-variables.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/03-variables.ts).
글 읽기 →04-functions.ts
04-functions.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/04-functions.ts).
글 읽기 →05-interfaces.ts
05-interfaces.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/05-interfaces.ts).
글 읽기 →06-classes.ts
06-classes.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/06-classes.ts).
글 읽기 →