Lesson 5 of 8
Conditional Types & `infer`
Conditional types express 'if T extends U, then X, else Y' at the type level. They are distributed over union types and can use `infer` to extract parts of a type. Built-in utility types like `ReturnType`, `Awaited`, and `Parameters` are all implemented with conditional types.
Conditional Types & infer - Type-Level Logic
// ── Basic conditional type ────────────────────────────────────
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<number>; // false
type C = IsString<"hello">; // true (literal string extends string)
// ── Distribution over unions ──────────────────────────────────
// When T is a union, conditional type is applied to EACH member:
type ToArray<T> = T extends unknown ? T[] : never;
type D = ToArray<string | number>; // string[] | number[]
type NonNullable2<T> = T extends null | undefined ? never : T;
type E = NonNullable2<string | null | undefined>; // string
// ── infer - extract part of a type ───────────────────────────
// infer introduces a TYPE VARIABLE within an extends clause:
// Extract element type from an array:
type ElementOf<T> = T extends (infer Item)[] ? Item : never;
type F = ElementOf<string[]>; // string
type G = ElementOf<Task[]>; // Task
type H = ElementOf<number>; // never (number is not an array)
// Extract return type (how ReturnType is implemented):
type MyReturnType<T> = T extends (...args: unknown[]) => infer R ? R : never;
type I = MyReturnType<() => string>; // string
type J = MyReturnType<(n: number) => boolean>; // boolean
// Extract parameter types:
type FirstParam<T> = T extends (first: infer F, ...rest: unknown[]) => unknown ? F : never;
type K2 = FirstParam<(name: string, age: number) => void>; // string
// ── Awaited - unwrap nested Promises ─────────────────────────
type MyAwaited<T> = T extends PromiseLike<infer U> ? MyAwaited<U> : T;
type L = MyAwaited<Promise<string>>; // string
type M = MyAwaited<Promise<Promise<number>>>; // number (recursive!)
// ── Practical: UnwrapApiResponse ─────────────────────────────
type ApiResponse<T> = { success: boolean; data: T; error?: string };
type UnwrapApiData<T> = T extends ApiResponse<infer D> ? D : never;
type N = UnwrapApiData<ApiResponse<Task>>; // Task
type O = UnwrapApiData<ApiResponse<User[]>>; // User[]
// ── Real utility: make function callbacks optional ─────────────
type OptionalPromise<T> = T extends Promise<infer U> ? U | Promise<U> : T;
// ── Conditional type for deep property access safety ──────────
type DeepGet<T, K extends string> =
K extends `${infer First}.${infer Rest}`
? First extends keyof T
? DeepGet<T[First], Rest>
: never
: K extends keyof T
? T[K]
: never;
// DeepGet<{ a: { b: { c: string } } }, "a.b.c"> = stringCommon Mistakes
- Using conditional types when a utility type suffices - `NonNullable<T>` is cleaner than `T extends null | undefined ? never : T`. Reach for built-ins first.
- Forgetting distribution - `T extends string ? T[] : never` applied to `string | number` gives `string[] | never` = `string[]`, not `(string | number)[]`. Distribution is a feature, but can surprise you.
- Writing `infer R` and R being `never` - if infer can't match, it resolves to `never`. Always test conditional types with a concrete type to confirm `infer` matched what you expected.
Tip
Tip
Practice Conditional Types in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Conditional Types & `infer`
Practice Task
Note
Practice Task - (1) Write a working example of Conditional Types from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Conditional Types is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Conditional types express 'if T extends U, then X, else Y' at the type level.
- Using conditional types when a utility type suffices - `NonNullable<T>` is cleaner than `T extends null | undefined ? never : T`. Reach for built-ins first.
- Forgetting distribution - `T extends string ? T[] : never` applied to `string | number` gives `string[] | never` = `string[]`, not `(string | number)[]`. Distribution is a feature, but can surprise you.
- Writing `infer R` and R being `never` - if infer can't match, it resolves to `never`. Always test conditional types with a concrete type to confirm `infer` matched what you expected.
Finished this lesson?