node.js - 如何从打字稿中的数组类型中获取类型的索引号?
问题描述
考虑以下打字稿代码:
type Data = [string, number, symbol]; // Array of types
// If I want to access 'symbol' I would do this:
type Value = Data[2]; //--> symbol
// I need to get the index of the 'symbol' which is 2
// How to create something like this:
type Index = GetIndex<Data, symbol>;
我想知道是否有可能在“数据”类型中获取符号类型的索引。
解决方案
此解决方案以字符串格式返回键(字符串"2"
而不是数字2
)。
给定一个数组A
和一个值类型T
,我们使用映射类型来检查哪些键的A
值匹配T
。如果类型正确,则返回该键,否则返回never
。[never, never, "2"]
这给了我们一个表示匹配和不匹配键的映射元组。我们只想要值,而不是元组,所以我们[number]
在类型的末尾添加,这给了我们元组中所有元素的联合——在这种情况下,它就像"2"
这里never
被忽略的一样。
type GetIndex<A extends any[], T> = {
[K in keyof A]: A[K] extends T ? K : never;
}[number]
type Index = GetIndex<Data, symbol>; // Index is "2"
推荐阅读
- mysql - SQL 版本 MySQL 5.5 中的排序列
- outlook - 无法使用 MS Graph API 上传大型附件
- arrays - 如何将选定对象从一组对象推入一个对象数组
- python - Conv2D model.fit 的请求张量校正错误
- android - 使用 webview 加载特殊站点
- python - 如何在 tkinter 中调用我保存的 python 文件?
- python - 如何使用 NumPy 将包含字符串和浮点值的 CSV 文件读入二维数组
- python - 如何使用熊猫按国家/地区列将数据拆分为一个工作簿中的多个工作表
- computer-forensics - 在 windows 2000 中应用程序无法在 WIN32 模式下运行
- python - Pycrypto:在 ECB 模式下使用 AES 进行“双重加密”不会产生明文