【问题标题】:How do I check that String Literal Types contain a value in TypeScript?如何检查字符串文字类型是否包含 TypeScript 中的值?
【发布时间】:2020-02-23 17:11:46
【问题描述】:

我想检查str是否在Name

有可能吗?

/* 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

【问题讨论】:

标签: typescript union-types


【解决方案1】:

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

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

【讨论】:

  • 我明白了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-08-05
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2012-05-06
  • 2018-05-06
  • 2021-11-10
相关资源
最近更新 更多