TSTypeScript
AdvancedLesson 13 of 15

Conditional Types, infer & Template Literals – TypeScript

Types with "if-then" logic and strings at the type level.

A conditional type T extends U ? X : Y picks a type depending on a condition – like a ternary at the type level:

type IstString<T> = T extends string ? "ja" : "nein";
type A = IstString<string>;      // "ja"
type B = IstString<number>;      // "nein"

type NichtNull<T> = T extends null | undefined ? never : T;
type C = NichtNull<string | null>;      // string

// For unions the type is distributive:
type D = IstString<string | number>;    // "ja" | "nein"

With infer you pull types out of structures. This is how ReturnType, Awaited and Parameters are built:

type ElementVon<T> = T extends (infer U)[] ? U : T;
type E1 = ElementVon<string[]>;                  // string
type E2 = ElementVon<number>;                    // number

type Rueckgabe<T> = T extends (...args: never[]) => infer R ? R : never;
type R1 = Rueckgabe<() => Promise<number>>;      // Promise<number>

type Ausgepackt<T> = T extends Promise<infer V> ? Ausgepackt<V> : T;
type V1 = Ausgepackt<Promise<Promise<string>>>;  // string

Template literal types assemble strings at the type level and generate all combinations in the process:

type Ereignis = "klick" | "hover";
type Handler = `on${Capitalize<Ereignis>}`;       // "onKlick" | "onHover"

type Seitenrand = `margin-${"oben" | "unten"}`;    // "margin-oben" | "margin-unten"
type PxWert = `${number}px`;

const breite: PxWert = "120px";
// const falsch: PxWert = "120";   // Error

A practical example: extracting parameters from a route string:

type RoutenParameter<S extends string> =
  S extends `${string}:${infer P}/${infer Rest}`
    ? P | RoutenParameter<Rest>
    : S extends `${string}:${infer P}`
      ? P
      : never;

type P = RoutenParameter<"/nutzer/:id/beitraege/:beitragId">;   // "id" | "beitragId"
WarningRecursive types are powerful, but also slow and hard to debug. Use them sparingly – simple unions and generics are often enough.