【问题标题】: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