Issue
consider the following typescript code:
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>;
I want to know if there is a possibility to get the index of symbol type in the type 'Data'.
Solution
This solution returns the keys in string format (string "2"
instead of number 2
).
Given an array A
and a value type T
, we use a mapped type to check which keys of A
have values that match T
. If the type is correct, we return that key and otherwise we return never
. That gives us a mapped tuple [never, never, "2"]
representing matching and non-matching keys. We want just the values, not the tuple, so we add [number]
at the end of our type which gives us the union of all elements in the tuple -- in this case it is just "2"
as never
is ignored here.
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"
Answered By - Linda Paiste
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.