Issue
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
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';
}
Answered By - crashmstr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.