TypeScript 在数组中找不到枚举

TypeScript doesn't found enum in array

我有一个这样的枚举:

export enum Roles {
   ADMIN, NONE;
}

我得到一个使用这个枚举的对象。对象:

export interface User {
   name: string;
   roles: Roles[];
}

我通过网络请求和 json 获得了它。收到web请求后,记录填好的对象:

{ name: 'Admin', roles: Array(1) }

角色数组为:

roles: ['ADMIN']

所以,我尝试检查用户是否像这样具有管理员角色:

user.roles.includes(Roles.ADMIN);

但它总是 return 错误。我也试过 user.roles.indexOf(Roles.ADMIN) != -1 但结果是一样的。

经过一些搜索,我看到多个 post 在谈论 Object.values()。我尝试用这种方法打印,或者使用 includes,但我得到了相同的结果。

我该怎么办?

enum TypeScript 中的默认条目 Numeric Enums0 和 auto-increment.

开始

如果您正在使用 API 或其他使用字符串表示的数据源,则需要将您的枚举实现为 String Enum

While string enums don’t have auto-incrementing behavior, string enums have the benefit that they “serialize” well. In other words, if you were debugging and had to read the runtime value of a numeric enum, the value is often opaque - it doesn’t convey any useful meaning on its own (though reverse mapping can often help). String enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member itself.

因此对于您的代码,您可以这样做:

export enum Roles {
  ADMIN = 'ADMIN',
  NONE = 'NONE';
}

打字稿中的枚举默认具有数值,因此在您的情况下 'ADMIN' = 0,因此 user.roles.includes(Roles.ADMIN); 永远不会 return 为真。一种选择是将您的枚举设置为类似这样的字符串值

export enum Roles {
  ADMIN = 'ADMIN', 
  NONE = 'NONE'
}

然后使用 user.roles.includes(Roles.ADMIN); 应该 return true