I have defined the following type:
type Admin: \'ADMIN\' | \'AGENT\';
I have a function that returns the user role from local storage:
You should create a type guard:
function isAdmin(arg: string): arg is Admin {
return arg === 'ADMIN' || arg === 'AGENT';
}
Then in your code:
let role: string = localStorage.getItem('role');
if (isAdmin(role)) {
... here role has the type Admin ...
}
The type guard is a special form of the function where the return makes an assertion about the type of its argument. The compiler then knows that when the function returns true
the argument had the specified type.
Unfortunately there's no way to do this without repeating the strings and writing an explicit test at least once but at least you can write the code once and use it to extend the type checking to safely cover the value.
Types are removed during compilation so you cannot use them for comparison. You can use a string based enum:
enum Role {
"ADMIN",
"AGENT"
}
let role = localStorage.getItem("role");
if (role && role in Role) {
console.log("role exists");
};