Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create a typeScript type ElementType<T> that extracts the type of elements

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading