How can I create a TypeScript utility type ElementType that extracts type of elements in an array of type T?
Ex:
type NumberArrayElement = ElementType<number[]>;, NumberArrayElement will be number
I tried using a conditional type to extract the element type of an array.
>Solution :
Welcome to Stackoverflow 🙂
you can set ElementType<T> like this:
type ElementType<T> = T extends (infer U)[] ? U : never;
ex:
type NumberArrayElement = ElementType<number[]>; //number
type StringArrayElement = ElementType<string[]>; //string
this checks if T is an array. If it is an array it extracts and returns the type of the elements inside the array (using infer U), Else ff T is not an array it returns never
Hope this helps!