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

Unwrapping Array Element Types

Extract the element type from an array type using conditional types to handle both arrays and non-arrays.

Unwrapping Array Element Types

What you'll learn: How to extract the inner element type from an array type using conditional types, while gracefully handling both array and non-array inputs.

The Problem

When working with generic types, you often receive a type that might be an array, and you need to "unwrap" it to get the element type inside. For example, if you have string[], you want to extract string. If you have number[], you want number.

The Pattern

You can build a conditional type that checks if a type is an array and extracts its element type using infer:

type Unwrap<T> = T extends (infer U)[] ? U : T;

This reads as: "If T extends an array of some type U, return U. Otherwise, return T unchanged."

How It Works

The infer keyword introduces a type variable U that TypeScript infers from the array pattern. When T is string[], TypeScript matches the pattern (infer U)[] and infers U = string.

type A = Unwrap<string[]>;     // string
type B = Unwrap<number[]>;     // number
type C = Unwrap<boolean>;      // boolean (unchanged)
type D = Unwrap<Array<Date>>;  // Date

Notice that non-array types pass through unchanged. This makes your unwrap utility safe to use even when you're uncertain whether the input is an array.

Real-World Applications

This pattern appears frequently when building generic utilities that handle both single values and collections, like extracting response data types from API functions or flattening nested type structures.

Key Takeaway: Use T extends (infer U)[] ? U : T to safely extract array element types, with infer capturing the inner type and the false branch preserving non-array types unchanged.