'TypeScript doesn't found enum in array

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 ?



Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheFlorinator