How to check if a given value is in a union type array

后端 未结 3 775
醉梦人生
醉梦人生 2021-01-18 04:13

I have an array of given union type, then wants to check if a string from a superset of the union type is contained in the array (runtime check):



        
3条回答
  •  有刺的猬
    2021-01-18 04:51

    I have found a potentially safer solution to this problem:

    const knownStrings = {
      abc: true,
      def: true,
    };
    
    const isKnownString = (name: string): name is keyof typeof knownStrings => name in knownStrings;
    

    This doesn't require any typecasting, the only downside is the redundant true values.

提交回复
热议问题