【问题标题】:Mapping Enum to Type of keys or values将枚举映射到键或值的类型
【发布时间】:2020-08-01 19:58:16
【问题描述】:

使用 Typescript 我想将 Enum 转换为

type keys = "key1"| "key2"
// or
type values = "value1" | "value2"

我可以在课堂上做到这一点

class C { a: number; b: string;}
type Keys = keyof C; // "x" | "y"
type Values = C[keyof C]; // string | number

我想做的事

enum Roles {Admin = "admin", Client = "client"};
? --> type Keys = ...; // "Admin" | "Client" 
? --> type Values = ...; // "admin" | "client"; 

这可能有点帮助

enum Roles {Admin = "admin", Client = "client"};

type values = {[K in Roles]: K}  // { admin: Roles.Admin; client: Roles.Client; }

【问题讨论】:

    标签: typescript types enums type-conversion


    【解决方案1】:

    使用枚举我不知道该怎么做,但你可以使用类型来实现你想要的:

    type RolesType = { Admin: "admin", Client: "client"}
    
    type Keys = keyof RolesType    // "Admin" | "Client"
    type Values = RolesType[Keys]  // "admin" | "client"
    

    【讨论】:

      【解决方案2】:

      虽然您可以很容易地获得枚举键 keyof typeof Roles(这很好解释 here),但不幸的是,不可能获得枚举值联合类型。有关更多详细信息,请参阅类似问题的 this answer。一种解决方法可能是使用 Object 而不是枚举作为 JeromeBu suggested:

      type Roles = { Admin: "admin", Client: "client" };
      type Keys = keyof Roles;
      type Values = Roles[Keys];
      

      【讨论】:

        猜你喜欢
        • 2019-04-09
        • 1970-01-01
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-03
        相关资源
        最近更新 更多