Checking validity of string literal union type at runtime?

前端 未结 7 1533
孤独总比滥情好
孤独总比滥情好 2020-12-03 04:16

I have a simple union type of string literals and need to check it\'s validity because of FFI calls to \"normal\" Javascript. Is there a way to ensure that a certain variabl

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 05:01

    using type is just Type Aliasing and it will not be present in the compiled javascript code, because of that you can not really do:

    MyStrings.isAssignable("A");
    

    What you can do with it:

    type MyStrings = "A" | "B" | "C";
    
    let myString: MyStrings = getString();
    switch (myString) {
        case "A":
            ...
            break;
    
        case "B":
            ...
            break;
    
        case "C":
            ...
            break;
    
        default:
            throw new Error("can only receive A, B or C")
    }
    

    As for you question about isAssignable, you can:

    function isAssignable(str: MyStrings): boolean {
        return str === "A" || str === "B" || str === "C";
    }
    

提交回复
热议问题