Get the Element type from an Array type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 1, 2022

banner

Check out my new book

Get the Element type from an Array type in TypeScript #

To get th element type from an array type, use a condition type with an infer declaration to infer the type of an element in the array. TypeScript will fill in the type of the element, and we can return it in the true branch of the conditional type.

index.ts
type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[] ? ElementType : never; const arr1 = ['a', 'b']; // 👇️ type T1 = string type T1 = ArrElement<typeof arr1>; const arr2 = ['a', 1]; // 👇️ type T2 = string | number type T2 = ArrElement<typeof arr2>;

The type alias takes a generic of the type of the array.

We used a conditional type the type of the array extends the inferred type of the array element.

Conditional types are very similar to a ternary operator.

If the expression before the question mark evaluates to a true, we return the type before the colon, otherwise return the type after the colon.

Here is an example of how conditional types work.

index.ts
interface Person { name: string; } interface Employee extends Person { id: number; } // 👇️ string type T3 = Employee extends Person ? string : number;

We used the infer keyword to have TypeScript fill in the type of the array element and return it.

Here is an oversimplified version of how the conditional type in the original example works.

index.ts
// 👇️ type T10 = string type T10 = string[] extends string[] ? string : never;

And here is the original code snippet.

index.ts
type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[] ? ElementType : never; const arr1 = ['a', 'b']; // 👇️ type T1 = string type T1 = ArrElement<typeof arr1>;

At the moment there is nothing that prevents the type to get passed a generic that is not an array.

You can use a type guard to make sure that the type alias is only used with an array.

index.ts
type ArrElement<ArrType extends readonly unknown[]> = ArrType extends readonly (infer ElementType)[] ? ElementType : never; const str = 'hello'; // ⛔️ Error: Type 'string' does not satisfy // the constraint 'readonly unknown[]'.ts(2344) type T1 = ArrElement<typeof str>;

Now the passed in generic can only be a type that extends unknown[], in other words an array containing elements of any type.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.