Lesson 27 +10 XP

Conditional Types & infer Keyword

Conditional Types & infer Keyword

Conditional types select one of two types based on a type relationship test: T extends U ? X : Y.

Conditional Types Syntax

type IsString<T> = T extends string ? true : false;

type A = IsString<string>;  // true
type B = IsString<number>;  // false

The infer Keyword

Inside conditional types, the infer keyword introduces a type variable to be deduced automatically.

// Custom ReturnType utility implementation:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : any;

function calculateScore(): number {
  return 100;
}

type Score = MyReturnType<typeof calculateScore>; // number!

Unpacking Array Element Types with infer

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

type Str = ElementType<string[]>; // string
type Num = ElementType<number>;   // number

TL;DR

  • Conditional types follow ternary logic: T extends U ? TrueType : FalseType.
  • infer R declares a type placeholder within a pattern matching check.
  • Enable complex type extraction from functions, promises, and arrays.