Advertisement
Beginner TypeScript, Conditional Types

How would you write a simple conditional type to extract the element type of an array?

Short answer

Combine a conditional type with the 'infer' keyword to capture and name the array's element type only when T actually matches the array shape.

Save TypeScript mock interview
Advertisement
AModel answer
Combine a conditional type with the 'infer' keyword to capture and name the array's element type only when T actually matches the array shape.
type ElementType<T> = T extends (infer U)[] ? U : never;
type A = ElementType<string[]>; // string
type B = ElementType<number>;   // never
Real-world example
Deriving the item type from a generic list type without manually specifying it twice.
Likely follow-ups
  • What does the resulting type become if T isn't an array at all?
Related topics