首页 > 解决方案 > 如何检查字符串文字类型是否包含 TypeScript 中的值?

问题描述

我想检查是否strName

可能吗?

/* imagination code */

type Name = 'a1' | 'a2' | .... | 'z100';

function isName(str: string): str is Name {
  switch (str) {
    case 'a1':
    case 'a2':
      // ...
    case 'z100':
      return true;
    default:
      return false;
  }
}

isName('alice') // -> true or false

标签: typescriptunion-types

解决方案


您不能从类型转到运行时检查。类型在编译时被擦除,因此您不能在运行时真正使用它们中的任何信息。但是,您可以采用另一种方式,从一个值转到一个类型:

const Name = ['a1', 'a2', 'z100'] as const // array with all values
type Name = typeof Name[number]; // extract the same type as before

function isName(str: string): str is Name {
  return Name.indexOf(str as any) !== -1; // simple check
}

isName('alice') // -> true or false


推荐阅读