考虑以下typescript代码:
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>;
我想知道是否有可能在类型'Data'中获得符号类型的索引。
此解决方案以字符串格式返回密钥(字符串"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"
操场上联系