TypeScript

Conditional Types Basics

admin by @admin ADMIN
17h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`T extends U ? X : Y` lets types branch on shape. Combine with `infer` to extract pieces of complex types — the building block under `ReturnType`, `Parameters`, and most utility libraries.
TypeScript
Raw
// Extract the resolved value of a Promise (or leave non-promise types alone).
type Unwrap<T> = T extends Promise<infer U> ? U : T;

type A = Unwrap<Promise<string>>;     // string
type B = Unwrap<number>;              // number

// Extract function argument types as a tuple.
type Args<F> = F extends (...args: infer P) => any ? P : never;

type FirstArg<F> = Args<F>[0];

const greet = (name: string, formal: boolean) => `Hello, ${name}`;
type Greeting = ReturnType<typeof greet>;   // string
type GreetArgs = Args<typeof greet>;        // [string, boolean]
type WhosName  = FirstArg<typeof greet>;    // string
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.