Saif Ali Khan
Saif Ali Khan

Reputation: 566

How to get the index number of a type from an Array type in typescript?

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'.

Upvotes: 2

Views: 1678

Answers (2)

LaughingThroll
LaughingThroll

Reputation: 21

Reply: is there a way to extract a literal number? like 2 – Eliav Louski

For transform to number you can use this utility type:

type ParseInt<T> = T extends `${infer N extends number}` ? N : never

Look to this question string to number

In this case it will look as:

type ParseInt<T> = T extends `${infer N extends number}` ? N : never
type GetIndex<A extends any[], T> = {
  [K in keyof A]:  A[K] extends T ? ParseInt<K> : never;
}[number]

type Index = GetIndex<Data, symbol>; // Index is 2 number

Upvotes: 2

Linda Paiste
Linda Paiste

Reputation: 42188

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"

Playground Link

Upvotes: 5

Related Questions