Conditional Types
A type that resolves to one of two types, chosen by a check done at compile time.
What is it?
An if statement branches on a value while the program runs. Types can branch too, but while the compiler checks your code, before anything runs.
A conditional type looks like a ternary, written with types: T extends U ? X : Y. It reads: "if T is assignable to U, the result is X; otherwise it's Y." So a type alias can give different results for different inputs, like true or false depending on whether the input is a string.
Combined with infer, conditional types get much more powerful. infer lets you extract and name part of a type inside the extends check, not just test it. That's how TypeScript expresses "the return type of this function" or "the type inside this array" as a type-level computation.
Explain like I'm 10
A conditional type is like a sorting machine on an assembly line. Each item (a type) is tested against a gauge and sent to one of two output belts depending on whether it fits, all decided by its shape before it reaches the end of the line.
Examples
A basic conditional type
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
// Conditional types are often used to build safer utility types:
type NonNullableCustom<T> = T extends null | undefined ? never : T;
type C = NonNullableCustom<string | null>; // stringIsString<T> checks at the type level whether T is assignable to string and resolves to the literal type true or false. NonNullableCustom uses the same idea to remove null/undefined from a type.
Extracting a type with infer
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type A = UnwrapPromise<Promise<string>>; // string
type B = UnwrapPromise<number>; // number (unchanged — not a Promise)
// TypeScript's own built-in ReturnType<T> works the same way:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: 1, name: "Ana" };
}
type User = MyReturnType<typeof getUser>; // { id: number; name: string }infer U adds a new type variable, U, which TypeScript fills in by matching Promise<infer U> against the actual type. That pulls out whatever is inside the Promise. Applied to a function's return position, the same trick is how the built-in ReturnType<T> works.
How it works
For T extends U ? X : Y, the compiler checks structurally, at compile time, whether every value of T is also a valid U. If so, the result is X; if not, Y.
With infer inside the extends clause, the compiler matches the whole shape (like Promise<...> or a function signature) against T. Whatever lines up with the infer placeholder is bound to the new type variable, which you can use in the X branch.
If T is a union, the check runs against each member separately and the results are combined into a union. This is a distributive conditional type.
Why does it exist?
Some type logic must branch on what kind of type it sees: getting the value out of a Promise type, pulling a function's return type from its signature, or filtering a union to members that match a pattern. Conditional types (with infer) express that branching and extraction directly. Without them, these transformations couldn't be written generically.
When to use it
Use a conditional type for a reusable, generic transformation whose result depends on the input's shape: extracting part of a wrapped type, building utilities beyond the built-ins, or filtering a union with a structural test.
When not to use it
Everyday application code rarely needs them; they mostly live in library and utility-type code. If a union, mapped type or built-in utility type does the job, use that. Conditional types (especially with infer) are much harder to read at a glance.
Common mistakes
Expecting a conditional type to run once. When T is a union, it's checked against each member separately (distributive conditional types), which can produce a broader union than expected.
Using
inferoutside anextendsclause. It's only valid inside a conditional type's check.Using conditional types for logic that would read more clearly as a plain union or a simpler mapped type.
Practice exercises
- Easy:
Write a conditional type
IsArray<T>that resolves totrueif T is an array type, andfalseotherwise. - Medium:
Write a conditional type
ElementType<T>that usesinferto extract an array type's element type (e.g.ElementType<string[]>isstring). - Hard:
Write a conditional type
Flatten<T>that, givenTorT[], always resolves toT: it removes one level of array wrapping if present and leaves non-array types unchanged.
Interview questions
What is a conditional type?
A type expression T extends U ? X : Y that resolves to X if T is assignable to U, and to Y otherwise, evaluated at compile time.
What does the `infer` keyword do inside a conditional type?
It adds a new type variable that the compiler fills in by matching the pattern (like Promise<infer U>) against the actual type, so you can extract part of it for the result.
What is a distributive conditional type?
When the checked type is a union, the condition is applied to each member separately and the results are combined into a union, instead of checking the whole union once.
Does a conditional type always distribute whenever T is a union, or is there a requirement for that to happen?
Only when the checked type is a naked type parameter, used directly with nothing around it. Wrapping it, as in [T] extends [U] ? X : Y, stops distribution, so the union is checked as a whole.
How do you deliberately prevent a conditional type from distributing over a union?
Wrap both sides of extends in a one-element tuple: [T] extends [U] ? X : Y. [T] is no longer a naked type parameter, so the whole union is checked against U at once.
Given `type ToArray<T> = T extends any ? T[] : never;`, what does `ToArray<string | number>` resolve to?
string[] | number[]. T is naked, so it distributes: string gives string[], number gives number[], and the results are unioned.
Given `type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;`, what does `ToArrayNonDist<string | number>` resolve to, and how does that differ from the distributive version?
(string | number)[]. The tuple wrapping stops distribution, so the whole union becomes one array type instead of a union of two array types.
What happens when `infer` sits in a position where multiple union members could each match a different candidate, e.g. inferring the return type from `(() => string) | (() => number)`?
TypeScript infers a union of the candidates, here string | number, because in a covariant (output) position multiple matches combine as a union.
How does inference differ when `infer` appears in a contravariant position (a function parameter) versus a covariant position (a return type)?
In a covariant position, candidates combine into a union. In a contravariant position, they combine into an intersection, because a parameter type that still accepts everything the wider type did must satisfy every candidate at once.
Write the conditional type that reimplements the built-in `Parameters<T>`.
type MyParameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;. infer P captures the whole parameter list as a tuple from the ...args rest position.
Why can't a simple, non-recursive conditional type like `T extends Promise<infer U> ? U : T` fully unwrap `Promise<Promise<Promise<string>>>` down to `string`?
It unwraps one layer per evaluation and returns U as matched, without checking it again. Full unwrapping needs recursion: type Await<T> = T extends Promise<infer U> ? Await<U> : T; reapplies itself until T is no longer a Promise.
What does the recursive `type Await<T> = T extends Promise<infer U> ? Await<U> : T;` resolve to for `Await<Promise<Promise<string>>>`, and how does the recursion terminate?
string. Each step strips one Promise layer (Promise<string>, then string). Once T no longer extends Promise<infer U>, the : T branch returns the final non-Promise type.
What limit does TypeScript impose on recursive conditional types, and what happens if you exceed it?
There's a cap on recursion depth. Exceeding it gives a compile error ("Type instantiation is excessively deep and possibly infinite") instead of looping forever, since the compiler can't always tell deep-but-finite recursion from infinite recursion.
How is a conditional type with `infer` different from a function overload for expressing "the return type depends on the input"?
An overload lists a fixed set of input/output signatures, picked at the call site. A conditional type is one reusable rule that works for any input matching the pattern, including inputs the author never listed.
How would you write a conditional type `Flatten<T>` that turns `string[]` into `string` but leaves plain `string` unchanged?
type Flatten<T> = T extends (infer U)[] ? U : T;. If T is an array, infer U captures the element type and the result is U; otherwise : T returns T unchanged.
`type ElementType<T> = T extends Array<infer U> ? U : never;` applied as `ElementType<string | number[]>` produces `number`, not something involving `string`. Is that a bug?
No, it's distribution. T is naked, so each member is checked separately: string doesn't match and gives never; number[] matches and gives number. never | number is just number, since never disappears from a union.
Why does `type IsNever<T> = [T] extends [never] ? true : false;` need the tuple-wrapping trick instead of `T extends never ? true : false`?
never is the "empty union." Distributing over a naked never runs no branches and resolves straight to never. Wrapping in [T] extends [never] stops distribution, so the check runs and returns true or false.
How could a conditional type detect whether a given type is specifically `any`?
type IsAny<T> = 0 extends 1 & T ? true : false;. Only for any does 1 & T collapse to any, making 0 extends any true. For every other type, 1 & T is 1 or never, which 0 doesn't extend, so the result is false.
How is checking `T extends unknown` different from checking `T extends any` in a conditional type?
T extends unknown is always true and, as a naked check, still distributes over unions, so it's often used as a no-op that triggers distribution. T extends any is a special case: any bypasses most type rules, so checks against it can behave inconsistently and are usually avoided as a real test.
Write a conditional type `NonFunctionKeys<T>` that resolves to a union of just the property names of T whose values are not functions.
type NonFunctionKeys<T> = { [K in keyof T]: T[K] extends (...args: any) => any ? never : K }[keyof T];. The mapped type turns function-valued keys into never and keeps the rest as themselves; indexing with [keyof T] collects the survivors into one union.
Why do conditional types need to exist — couldn't the same transformations be written as separate, non-generic type aliases for each case?
The point is reuse across types not known in advance. A conditional type says "if the type you give me has this shape, produce this related type" once, so it works for user types the author never saw. Separate aliases would mean rewriting the logic for every new type.
`type Includes<T, U> = T extends U ? true : false;` called as `Includes<string | number, string>` produces `boolean` instead of the expected `true`. Why?
Distribution. T is naked, so each member is checked: string extends string is true, number extends string is false, and true | false displays as boolean. To test the whole union, use [T] extends [U] ? true : false.
Is a conditional type computed once globally, or re-evaluated per use?
It's evaluated separately for each distinct set of type arguments it's used with. Identical instantiations are usually cached for performance, but each concrete substitution is evaluated on its own.