`string literal union type` over `enum`

235 阅读1分钟

使用枚举具有诸多好处:Type safety 和 documentation(否则无法得知值的全貌)。但当我们的枚举值都是字符串时,应当优先考虑 union 类型来构造我们的类型。因为:

  • 字符串已具备可读性,如果采用 enum 还得写两遍(key 和 value)
type RoleEnum = 'admin' | 'editor' | 'reader' | 'anonymous'
enum UserType {
    Admin = 'admin',
    Editor = 'editor',
    Reader = 'reader',
    Anonymous = 'anonymous'
}
  • 其次无需导入即可使用
function deleteUser(user: User) {
    if (user.type === 'admin') {
        //... make the call for delete
    } else {
        // ... show some error that the user does not have the permission to do this
    }
}
import { UserType } from '../types/user-type';

function deleteUser(user: User) {
    if (user.type === UserType.Admin) {
        //... make the call for delete
    } else {
        // ... show some error that the user does not have the permission to do this
    }
}

参考

danielbarta.com/typescript-…

更多阅读

如何获取 enum 的值构成的类型