I've recently started learning TypeScript and exploring its functionalities. I could use some assistance in deepening my understanding.
Within our angular2 application, we have defined an enum
for privileges as follows:
export enum UserPrivileges{
SUPER,
USER,
GUEST
}
We utilize this type in a function definition where it is represented as an array of the enum type:
checkPrivileges(userPrivileges: UserPrivileges[]) {...}
The approach we have taken to determine user privileges is:
this.isSuperUser = userPrivileges.includes(UserPrivileges[UserPrivileges.SUPER]);
Issue
TypeScript raises an error stating that "Argument of type 'string' is not assignable to type 'UserPrivileges'" due to the use of the Array.prorotype.includes()
method call (similar issue with .indexOf()
.)
I have attempted various forms of explicit casting without success:
this.isSuperUser = userPrivileges.includes(<string>UserPrivileges[UserPrivileges.SUPER]);
this.isSuperUser = userPrivileges.includes(UserPrivileges[UserPrivileges.<string>SUPER]);
We managed to bypass the TypeScript error by modifying the function signature to:
checkPrivileges(userPrivileges: string[]) {...}
...but this defeats the purpose of utilizing types.
This seems like a common scenario, but perhaps there's a necessary decorator or method I'm overlooking? Is there something that needs to be added to the enum type definition to allow it to be interpreted as a string?
Edit
To clarify, our backend sends privilege tokens as strings in an array, such as
userPrivileges = ["SUPER", "GUEST", "USER"]
. The UserPrivileges
enum type was intended to mirror this structure.
The old method, which functioned correctly (expecting true
):
userPrivileges.indexOf(UserPrivileges[UserPrivileges.SUPER]) > -1;
Because
UserPrivileges.SUPER
equates to0
(due to the emitted JS explanation)UserPrivileges[0]</code then results in the string <code>"SUPER"
- ...which matches a value in
userPrivileges[]
from the backend.
However, these will both inaccurately (yet expectedly) return false
userPrivileges.includes(UserPrivileges.SUPER);
userPrivileges.indexOf(UserPrivileges.SUPER) > -1;
for the same reasons explained above: the server-provided userPrivileges[]
does not contain a value of 0
.
"Using an enum value on itself will yield back the string." In order for the suggested solution to function properly, it appears that I would need to employ the type's numeric index UserPrivileges[0]
to retrieve the corresponding string for comparison with the API response?