Home > Back-end >  TypeScript doesn't found enum in array
TypeScript doesn't found enum in array

Time:02-25

I have an enum like that:

export enum Roles {
   ADMIN, NONE;
}

I get an object which use this enum. The object:

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

I get it with a web request and json. After receiving the web request, I log the object which is well filled:

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

The role array is:

roles: ['ADMIN']

So, I try to check if the user as the admin role like that:

user.roles.includes(Roles.ADMIN);

But it always return false. I also tried user.roles.indexOf(Roles.ADMIN) != -1 but it's the same result.

After some search, I see multiple post talking about Object.values(). I tried to print with this method, or use includes, but I get the same result.

How can I do ?

CodePudding user response:

enum entries in TypeScript default Numeric Enums that start at 0 and auto-increment.

If you are working with an API or other data source that uses string representations, you need to implement your enum as a 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.

So for your code, you would do this:

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

CodePudding user response:

Enums in typescript by default have numeric values, so you in your case 'ADMIN' = 0, therefore user.roles.includes(Roles.ADMIN); will never return true. One option is to set your Enums to string values something like this

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

Then using user.roles.includes(Roles.ADMIN); should return true

  • Related