枚举进阶
枚举高级用法与替代方案
1. 枚举类型
// 数字枚举
enum Direction {
Up,
Down,
Left,
Right,
}
// 字符串枚举
enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
}
// 异构枚举(不推荐)
enum BooleanLike {
No = 0,
Yes = 'YES',
}
2. const 枚举
const enum Colors {
Red = '#FF0000',
Green = '#00FF00',
Blue = '#0000FF',
}
let color = Colors.Red; // 编译为 '#FF0000'
3. 枚举与类型
// 枚举成员类型
enum ShapeKind {
Circle,
Square,
}
interface Circle {
kind: ShapeKind.Circle;
radius: number;
}
interface Square {
kind: ShapeKind.Square;
size: number;
}
type Shape = Circle | Square;
// 枚举合并
enum Weekday {
Mon,
Tue,
Wed,
}
enum Weekday {
Thu = 3,
Fri,
Sat,
Sun,
}
4. 枚举替代方案
// as const 对象
const Direction = {
Up: 'UP',
Down: 'DOWN',
Left: 'LEFT',
Right: 'RIGHT',
} as const;
type Direction = (typeof Direction)[keyof typeof Direction];
// 'UP' | 'DOWN' | 'LEFT' | 'RIGHT'
// 联合类型
type Status = 'active' | 'inactive' | 'pending';
// 辅助函数
function enumFromObj<T extends Record<string, string>>(obj: T) {
return { ...obj, values: Object.values(obj) as T[keyof T][] };
}