Checking validity of string literal union type at runtime?

前端 未结 7 1482
孤独总比滥情好
孤独总比滥情好 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:09

    You can use "array first" solution to create string literals and use it as usual. And use Array.includes() at the same time.

    const MyStringsArray = ["A", "B", "C"] as const;
    MyStringsArray.includes("A" as any); // true
    MyStringsArray.includes("D" as any); // false
    
    type MyStrings = typeof MyStringsArray[number];
    let test: MyStrings;
    
    test = "A"; // OK
    test = "D"; // compile error
    
    0 讨论(0)
提交回复
热议问题