打字稿字符串枚举逆映射

Typescript string enum inverse mapping

我有一个字符串枚举定义如下:

export enum UserRole {
  SHOP_DESIGNER = 'DG_PF00-CorpID-Designa_Shop-Designers',
  SHOP_EMPLOYEE = 'DG_PF00-CorpID-Designa_Shop-Employees',
  LOGISTICS_TEAM = 'DG_PF00-CorpID-Designa_Logistics',
}

我想创建一个从枚举字符串值到它的枚举类型的类型安全映射:

const USER_ROLE_NAMES<string, UserRole> = ....

所以我可以通过查询地图来解析任意值:

let role: UserRole

// role = SHOP_DESIGNER 
role = USER_ROLE_NAMES.get('DG_PF00-CorpID-Designa_Shop-Designers')

// role = SHOP_DESIGNER 
role = USER_ROLE_NAMES.get('DG_PF00-CorpID-Designa_Shop-Employees')

// role = SHOP_DESIGNER 
role = USER_ROLE_NAMES.get('DG_PF00-CorpID-Designa_Logistics')

// role = undefined
role = USER_ROLE_NAMES.get('some arbitrary string value which is not an enum value')

我已经尝试过以下方法:

export const USER_ROLE_NAMES = new Map(Object.entries(UserRole).map(([key, value]: [string, UserRole]) => [value, key]));

但是USER_ROLE_NAMES的类型是Map<UserRole, string>,无法用字符串查询map

如果我反转映射

export const USER_ROLE_NAMES = new Map(Object.entries(UserRole).map(([key, value]: [string, UserRole]) => [key, value]));

那么类型是正确的,但是映射是错误的('DESIGNA_USER' => 'DG_PF00-CorpID-Designa_Users',...而不是'DG_PF00-CorpID-Designa_Users' => 'DESIGNA_USER',...

在运行时,UserRole.SHOP_DESIGNER的值实际上是'DG_PF00-CorpID-Designa_Shop-Designers',而不是'SHOP_DESIGNER'。所以你要求的映射看起来像这样(在运行时):

const theMapping ={
  'DG_PF00-CorpID-Designa_Shop-Designers': 'DG_PF00-CorpID-Designa_Shop-Designers',
  ...
}

如果你想要这个“枚举值”->“枚举成员”映射,你可以这样构造它:TypeScript playground link

export enum UserRole {
  SHOP_DESIGNER = 'DG_PF00-CorpID-Designa_Shop-Designers',
  SHOP_EMPLOYEE = 'DG_PF00-CorpID-Designa_Shop-Employees',
  LOGISTICS_TEAM = 'DG_PF00-CorpID-Designa_Logistics',
}

const mapping: Map<string, UserRole> = new Map(Object.values(UserRole).map(
    (memberValue) => [`${memberValue}`, memberValue] as const
))

let role1 = mapping.get('DG_PF00-CorpID-Designa_Shop-Designers')
let role2 = mapping.get('unknown')