Get the Element type from an Array type in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
2 min

banner

# Get the Element type from an Array type in TypeScript

To get the element type from an array type:

  1. Use a condition type with an infer declaration to infer the type of an element in the array.
  2. 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>;

get element type from array type

The code for this article is available on GitHub

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

We used a conditional type in the example.

Conditional types are very similar to the ternary operator.

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

# Using conditional types

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;

using conditional types

The code for this article is available on GitHub

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

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 sample.

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 from getting 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.

Copyright ยฉ 2024 Borislav Hadzhiev