3

Say I have the type

type MyTypeArray = ['', 2, boolean]

How could I extract the type 2 | boolean when the array could be of an unknown length?

1 Answer 1

5

You can infer all elements but first. Use spread tuple operator: ..., just like in plain javascript


type ExtractTail<T extends any[]> = T extends [infer _, ...infer Tail] ? Tail : never

// [2, boolean]
type MyTypeArray = ExtractTail<['', 2, boolean]>

// 2 | boolean
type Union = MyTypeArray[number]

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

2 Comments

@johann1301s made an update.
You can also use a similar procedure to extract just the last element of a tuple: type LastValueOfTuple<T extends any[] | readonly any[]> = T extends [...infer Start, infer Last] ? Last : never; Not the question that was asked, but this is the article that appeared when I was searching for this answer.

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.