Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use typescript to extract all element type(s) from array except first

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?

like image 988
johann1301s Avatar asked Aug 12 '26 14:08

johann1301s


1 Answers

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]

like image 180
captain-yossarian Avatar answered Aug 15 '26 05:08

captain-yossarian