To ensure the type of a variable, create a type guard like this:
function checkIfAdmin(arg: string): arg is Admin {
return arg === 'ADMIN' || arg === 'AGENT';
}
Utilize the type guard in your code as shown below:
let role: string = localStorage.getItem('role');
if (checkIfAdmin(role)) {
... now 'role' is recognized as type Admin ...
}
A type guard function asserts the type of its argument with the returned value. By returning true
, the compiler understands the specified type.
Though it may involve repeating strings and explicit tests initially, using this approach allows you to write the code once and broaden the scope of type checking effectively.