Testing for String Literal Type in Typescript

前端 未结 2 1512
自闭症患者
自闭症患者 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-25 16:48

    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");
    };
    
    0 讨论(0)
提交回复
热议问题