Testing for String Literal Type in Typescript

前端 未结 2 1540
自闭症患者
自闭症患者 2021-01-25 16:07

I have defined the following type:

type Admin: \'ADMIN\' | \'AGENT\';

I have a function that returns the user role from local storage:

2条回答
  •  萌比男神i
    2021-01-25 16:41

    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.

提交回复
热议问题