1

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 ?

2 Answers 2

1

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';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.