2

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

1
  • Data.indexOf("symbol")? Commented Jan 17, 2021 at 20:41

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect!! Thanks
is there a way to extract a literal number? like 2
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.