简体   繁体   English

在 Typescript 中将类型定义为“来自枚举的所有可能性”

[英]Define type as “all possibilities from an enum” in Typescript

I have the following enum我有以下枚举

export enum USER_GROUPS {
  "Admin",
  "Design",
  "FrontEnd",
  "BackEnd"
}

And the following function以及以下 function

const isUserOfType = (userGroupId: number, userType: USER_GROUPS) => {
  return userGroupId === USER_GROUPS[userType];
};

Where在哪里

isUserOfType(2, "Design") // returns true
isUserOfType(1, "BackEnd") // returns false

The problem is the second param is not assignable to type: USER_GROUPS ... I could do the following问题是第二个参数不可分配给type: USER_GROUPS ...我可以执行以下操作

isUserOfType = (
    userGroupId: number,
    userType:
      | USER_GROUPS.Admin
      | USER_GROUPS.Design
      | USER_GROUPS.FrontEnd
      | USER_GROUPS.BackEnd
  ) => {
      return userGroupId === USER_GROUPS[userType];
    };

However, that is annoying to do on every function.然而,这对每个 function 来说都很烦人。 and defining a completely separate type defeats some of the purpose of an enum并且定义一个完全独立的类型违背了枚举的某些目的

As mentioned, you can use keyof typeof to get all the Enum keys:如前所述,您可以使用keyof typeof来获取所有 Enum 键:

export enum USER_GROUPS {
  "Admin",
  "Design",
  "FrontEnd",
  "BackEnd"
}

type USER_GROUPS_KEYS = keyof typeof USER_GROUPS;

const isUserOfType = (userGroupId: number, userType: USER_GROUPS_KEYS) => {
  return userGroupId === USER_GROUPS[userType];
};

isUserOfType(2, "Design") // returns true
isUserOfType(1, "BackEnd") // returns false

Personally I would use string enums or a string union type instead:我个人会使用字符串枚举或字符串联合类型:

export enum USER_GROUPS_V2 {
  "Admin" = "Admin",
}

export type USER_GROUPS_UNION_TYPE = 
  | "Admin"
  | "Design";

but if you're stuck with another data source that requires these to be numerical, then the above will work.但是,如果您遇到另一个要求这些数据源为数字的数据源,那么上述方法将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM