Skip to main content

enum

const ODirection = {
Up: 0,
Down: 1,
Left: 2,
Right: 3,
} as const;

// 达到类似 enum 的效果
type Direction = (typeof ODirection)[keyof typeof ODirection];

enum LogLevel {
ERROR,
WARN,
INFO,
DEBUG,
}
// 这样可以值匹配即可
type LogLevelStrings = keyof typeof LogLevel;

编译后的 ENUM

var Enum;
(function (Enum) {
Enum[(Enum['A'] = 0)] = 'A';
})(Enum || (Enum = {}));
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

Practice

// 使用的时候
export enum WecomSubjectType {
WecomRoom = 'WecomRoom',
WecomRobot = 'WecomRobot',
ExternalWechatUser = 'ExternalWechatUser',
ExternalWecomUser = 'ExternalWecomUser',
}

// 返回的时候 - 确保也能直接使用 string
export type WecomSubjectTypeCode = keyof typeof WecomSubjectType;