跳至正文
Wener Notes

enum

约 1 分钟阅读
标签:Enum
TypeScript
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

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

Practice

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

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

关联信息

反向链接、本文链接的其他页面和外部资料。

参考资料

其他外链1 条
最近更新commit b4d3722编辑