Script Valley
TypeScript: Complete Course from Zero
Advanced Types and Real-World PatternsLesson 6.2

Conditional types in TypeScript ternary logic at the type level

conditional type syntax, extends in conditional types, infer keyword, distributive conditional types, NonNullable explained

Conditional type syntax

type IsString = T extends string ? true : false;

type A = IsString; // true
type B = IsString; // false

Distributive conditional types

When T is a union, conditional types distribute over each member:

type Flatten = T extends Array ? Item : T;

type A = Flatten;      // string
type B = Flatten;        // number (no change)
type C = Flatten<(string|number)[]>; // string | number

infer keyword

infer captures a type inside a conditional check:

type UnpackPromise = T extends Promise ? R : T;

type A = UnpackPromise>; // string
type B = UnpackPromise;          // number

This is how the built-in Awaited and ReturnType are implemented. The infer variable only exists within the conditional branch where it was matched.

Up next

Template literal types in TypeScript dynamic string types

Sign in to track progress

Conditional types in TypeScript ternary logic at the type level โ€” Advanced Types and Real-World Patterns โ€” TypeScript: Complete Course from Zero โ€” Script Valley โ€” Script Valley