枚举
约 261 字小于 1 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › 基础入门 › 枚举
数字枚举
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
console.log(Direction.Up); // 0
console.log(Direction[0]); // "Up"(反向映射)指定初始值
enum Status {
Pending = 1,
Processing, // 2
Completed, // 3
Failed, // 4
}字符串枚举
enum Color {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
console.log(Color.Red); // "RED"
// 字符串枚举没有反向映射常量枚举
const enum Size {
Small = 'S',
Medium = 'M',
Large = 'L',
}
// const enum 在编译时被内联,不生成 JS 代码枚举的实际用法
enum HttpStatus {
OK = 200,
Created = 201,
BadRequest = 400,
Unauthorized = 401,
NotFound = 404,
InternalServerError = 500,
}
function handleResponse(status: HttpStatus) {
switch (status) {
case HttpStatus.OK: return '成功';
case HttpStatus.NotFound: return '未找到';
default: return '未知';
}
}小结
| 枚举类型 | 特点 | 适用场景 |
|---|---|---|
| 数字枚举 | 自增、反向映射 | 通用状态码 |
| 字符串枚举 | 含义明确、无反向映射 | API 常量 |
const enum | 编译内联、零开销 | 性能敏感场景 |
上一节:类型推断与类型断言 下一节:Interface 详解
