Basic infer Pattern: Extracting Array Element Types
You'll learn how to use TypeScript's infer keyword to extract the element type from an array type, unlocking powerful type-level pattern matching.
What Is This Pattern?
The infer keyword lets you extract and capture types from within other types. Think of it like destructuring, but for types instead of values. When you write T extends (infer U)[], you're asking TypeScript: "If T is an array type, please extract and give me the element type as U."
This is your first look at conditional type pattern matching—the foundation for many advanced TypeScript utilities.
The Core Pattern
type ElementOf<T> = T extends (infer U)[] ? U : never;
Let's break this down:
T extends (infer U)[]- "IsTassignable to an array type?"infer U- "If yes, capture the element type asU"? U : never- "Return the captured type, orneverif it's not an array"
Seeing It in Action
type ElementOf<T> = T extends (infer U)[] ? U : never;
type Numbers = ElementOf<number[]>; // number
type Strings = ElementOf<string[]>; // string
type Mixed = ElementOf<(string | number)[]>; // string | number
type NotArray = ElementOf<string>; // never
Notice how infer U "captures" whatever the element type is, then makes it available in the true branch of the conditional.
Why This Matters
Without infer, you'd have no way to extract types from generic structures. It's like having a sealed box—you can see it's an array, but you can't access what's inside. infer gives you that X-ray vision at the type level.
The Mental Model
Think of infer as a type-level variable declaration. When TypeScript matches the pattern (infer U)[], it binds whatever matches in that position to U, just like how pattern matching works in functional programming languages.
Key Takeaway: Use T extends (infer U)[] to extract array element types—this pattern lets you capture and reuse type information from generic array types, forming the basis of type-level programming in TypeScript.