首页 > 解决方案 > 如何从打字稿中的数组类型中获取类型的索引号?

问题描述

考虑以下打字稿代码:


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>;

我想知道是否有可能在“数据”类型中获取符号类型的索引。

标签: node.jstypescript

解决方案


此解决方案以字符串格式返回键(字符串"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"

游乐场链接


推荐阅读