Checking validity of string literal union type at runtime?

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

    Since Typescript 2.1, you can do it the other way around with the keyof operator.

    The idea is as follows. Since string literal type information isn't available in runtime, you will define a plain object with keys as your strings literals, and then make a type of the keys of that object.

    As follows:

    // Values of this dictionary are irrelevant
    const myStrings = {
      A: "",
      B: ""
    }
    
    type MyStrings = keyof typeof myStrings;
    
    isMyStrings(x: string): x is MyStrings {
      return myStrings.hasOwnProperty(x);
    }
    
    const a: string = "A";
    if(isMyStrings(a)){
      // ... Use a as if it were typed MyString from assignment within this block: the TypeScript compiler trusts our duck typing!
    }
    

提交回复
热议问题