typescript - 如何检查字符串文字类型是否包含 TypeScript 中的值?
问题描述
我想检查是否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
解决方案
您不能从类型转到运行时检查。类型在编译时被擦除,因此您不能在运行时真正使用它们中的任何信息。但是,您可以采用另一种方式,从一个值转到一个类型:
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
推荐阅读
- django - TypeError:“方法”对象不可下标 Python/django
- python - 如何一次切片熊猫数据框的所有元素?
- opencv - OpenCV中霍夫圆和minEnclosed圆检测圆的区别?
- python - Tensorflow 未在 GPT-2 程序中充分利用 GPU
- vega-lite - 在数据之间切换时重用 Vega-Lite 轴
- java - 如何在 JavaFX 应用程序上显示具有相对路径的图像?
- python - 从使用 Python 从 JavaScript/JSON 数组(POST 请求)加载数据的网站抓取数据
- c++ - 按字母顺序排列结构数组
- arrays - 为什么我不能使用模板文字在新对象中创建字符串作为键?
- angular - 从服务调用到组件时需要什么样的参数?ts(2554)