Skip to content

Instantly share code, notes, and snippets.

@ThaddeusJiang
Last active June 29, 2021 07:43
Show Gist options
  • Save ThaddeusJiang/12425c046cd09d9d56a9de3d35ba3646 to your computer and use it in GitHub Desktop.
Save ThaddeusJiang/12425c046cd09d9d56a9de3d35ba3646 to your computer and use it in GitHub Desktop.
TypeScript 使用 union 类型实现 enum 类型
// https://www.typescriptlang.org/play?#code/PTAEjztRRNMTwzDu3RaOUKe6gdeQFAGMD2A7AzgF1AAUBTAJwFsBLXXKnXUAXlAG9VRQySBDAEwBcoAOTd+wgDQdQAdzJV8JIcLkKSk6SQAeJdAFdFy7boPrUAX1A9GWPPgDcqfAE8ADiWLlqtetmagXd0wAM09KGjoGAG0AaxJnEIC3EkTScJ8GAF17UBARMT5hUAAfEVVFItLhY30KoA
// typescript playgroud 工作,实际项目中不工作
const permissions = ['read', 'write', 'execute'] as const;
type Permission = typeof permissions[number]; // 'read' | 'write' | 'execute'
// typescript playgroud 不工作,实际项目中工作
const Permissions = {
read: 'read',
write: 'write',
execute: 'execute'
} as const;
type Permission = typeof Permissions[keyof typeof Permissions]; // 'read' | 'write' | 'execute'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment