Course contentsShow
← TypeScript
Lesson 1452 of 1,79633. Inference Inversion PatternsFree lesson

Extracting Array Element Types

Create a utility type that extracts the element type from any array or readonly array type.

Extracting Array Element Types

What you'll learn: You'll learn how to create a utility type that extracts the element type from any array or readonly array type using inference inversion.

Understanding the Problem

When working with arrays in TypeScript, you often know you have an array but want to work with the type of elements inside that array. For example, if you have string[], you want to extract string. If you have readonly number[], you want to extract number.

This is a classic inference inversion pattern: instead of inferring what comes out of a function, you're extracting what's inside a type structure.

The Pattern

Using infer in a conditional type, you can extract array element types:

type ElementType<T> = T extends (infer E)[] ? E : never;

// Usage
type StringArray = string[];
type Element = ElementType<StringArray>; // string

type NumberArray = number[];
type Num = ElementType<NumberArray>; // number

The pattern works by asking: "If T extends an array of some type E, give me E, otherwise give me never."

Handling Readonly Arrays

To support both mutable and readonly arrays, use a union:

type ElementType<T> = T extends (infer E)[]
  ? E
  : T extends readonly (infer E)[]
  ? E
  : never;

type ReadonlyNumbers = readonly number[];
type Elem = ElementType<ReadonlyNumbers>; // number

Practical Applications

// Extract element type from complex arrays
type NestedArray = Array<{ id: number; name: string }>;
type Item = ElementType<NestedArray>; // { id: number; name: string }

// Use in generic functions
function firstElement<T extends unknown[]>(arr: T): ElementType<T> | undefined {
  return arr[0];
}

Key Takeaway: Use T extends (infer E)[] ? E : never to extract array element types, creating reusable type utilities that work with any array structure through inference inversion.