Course contentsShow
← TypeScript
Lesson 792 of 1,79618. Conditional TypesFree lesson

Basic infer Pattern: Extracting Array Element Types

Using infer to extract the element type from an array type, like T extends Array<infer U> ? U : never.

Basic infer Pattern: Extracting Array Element Types

What you'll learn: How to use infer inside a conditional type to extract the element type from an array, giving you powerful type-level introspection.

The Core Idea

The infer keyword lets you capture and name parts of a type pattern. When you write T extends Array<infer U>, you're essentially saying: "If T matches the pattern of an array, grab whatever type is inside it and call it U."

Think of infer like pattern matching in other languages. You're matching against a shape, and when the shape fits, you extract pieces of it.

The Pattern

Here's the fundamental structure for extracting array element types:

type ElementType<T> = T extends Array<infer U> ? U : never;

Let's break this down:

  • T extends Array<infer U> — "Does T match an array pattern?"
  • infer U — "If yes, capture the element type as U"
  • ? U — "Return that captured type"
  • : never — "If T isn't an array, return never"

Seeing It in Action

type StringArray = ElementType<string[]>;  // string
type NumberArray = ElementType<number[]>;  // number
type MixedArray = ElementType<(string | number)[]>;  // string | number

type NotArray = ElementType<string>;  // never
type NotArray2 = ElementType<{ value: number }>;  // never

The magic happens because TypeScript sees the array pattern, understands you want the "thing inside," and gives it to you.

Why This Matters

Without infer, you couldn't extract types from complex structures. This pattern is the foundation for building utilities like ReturnType, Awaited, and custom type transformations.

Key Takeaway: infer lets you capture type pieces from patterns — T extends Array<infer U> extracts the element type from an array, returning it if the pattern matches or never if it doesn't.