Conditional types
Choosing between two types with `T extends U ? X : Y`, so a type can branch on its input the way an expression branches on a value.
Conditional types
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A conditional type, written `T extends U ? X : Y`, picks `X` when `T` is assignable to `U` and `Y` otherwise; it is a ternary that runs on types instead of values.
- The `extends` in a conditional is a question about assignability, the same check the compiler runs when you pass an argument, not a statement about class inheritance.
- With a concrete type the condition resolves straight away; while `T` is still an unresolved type parameter, the conditional stays deferred until a real type arrives.
- Conditionals nest in the false branch to form a chain of cases, checked top to bottom, much like `else if`.
- Returning `never` from one branch removes a case, which is the basis for filtering types; how that works on unions is the subject of the distributive conditional types lesson.
- A function whose return type is a conditional usually can't have its body checked against each branch, so implementations rely on an assertion or switch to overloads.
Types that depend on other types
Generics let a type follow its input: identity<T>(x: T): T returns whatever came in. That covers the case where the output has the same type as the input. Plenty of real code doesn’t work that way. A fetch helper returns void when you pass a callback and a Promise when you don’t. A format function turns numbers into strings but leaves strings alone. The output type depends on the input type, and it depends on it through a decision.
Function overloads can describe a few such cases, one signature per input. They don’t compose, though: you can’t take an overload stack and reuse its logic inside another type. What’s needed is a way to write the decision itself as a type.
The syntax is a ternary
A conditional type looks like JavaScript’s conditional operator, moved into the type system:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
type C = IsString<string>; // true
Read T extends string ? true : false as “if T is assignable to string, the result is true, otherwise false.” There are always exactly two branches. Both are types, and either can be any type at all: a literal, an object, another generic, or another conditional.
extends means “is assignable to”
The keyword is the same one used in generic constraints, and it asks the same question. It isn’t about classes or inheritance. A extends B holds when every value of type A would also be accepted where a B is expected. That’s the check the compiler runs every time you pass an argument to a parameter.
type HasId<T> = T extends { id: number } ? "has id" : "no id";
type User = { id: number; name: string };
type Point = { x: number; y: number };
type U1 = HasId<User>; // "has id"
type U2 = HasId<Point>; // "no id"
type U3 = HasId<{ id: string }>; // "no id"
User never mentions { id: number }, yet it passes. It has an id of the right type, and structural typing says that’s enough. { id: string } fails because its id has the wrong type.
Think of it as a customs check at a border: the officer doesn’t care where a package was made, only whether its contents match the declared list. Extra items are fine. Missing or mismatched ones aren’t.
Chaining cases
Since a branch can hold any type, it can hold another conditional. Nesting in the false branch gives you an else if chain:
type TypeName<T> = T extends string
? "string"
: T extends number
? "number"
: T extends boolean
? "boolean"
: T extends (...args: never[]) => unknown
? "function"
: "object";
type N1 = TypeName<"a">; // "string"
type N2 = TypeName<() => void>; // "function"
type N3 = TypeName<Date>; // "object"
The conditions are tried top to bottom and the first that holds wins. Order matters for the same reason it does in a real if chain: a broad test near the top swallows cases meant for narrower tests below it.
Deferred until a real type arrives
A conditional only resolves once the compiler knows what T is. With a concrete type like User, it resolves right away. Inside a generic function, T is still a placeholder, so the conditional stays unresolved, or deferred. That has a practical consequence:
type Wrapped<T> = T extends string ? string[] : T;
function wrap<T>(value: T): Wrapped<T> {
if (typeof value === "string") {
return [value]; // Error: not assignable to type 'Wrapped<T>'
}
return value; // Error: not assignable to type 'Wrapped<T>'
}
Narrowing value with typeof doesn’t narrow T itself, so the compiler can’t match [value] to the true branch. The usual fix is an assertion inside the body, keeping the precise type on the outside where callers see it:
function wrapChecked<T>(value: T): Wrapped<T> {
const result = typeof value === "string" ? [value] : value;
return result as Wrapped<T>;
}
const w1 = wrapChecked("hi"); // string[]
const w2 = wrapChecked(5); // 5
The assertion is a promise you make, not one the compiler checks, so keep these bodies small. When there are only two or three input types, overloads are often clearer.
never as a delete key
One branch can return never, the type with no values. On its own, never is just an empty result. Combined with unions it becomes a filter:
type OnlyStrings<T> = T extends string ? T : never;
type S = OnlyStrings<"a" | 1 | "b" | true>; // "a" | "b"
That result might surprise you. The input was a union, and the conditional seems to have been applied to each member separately, with the nevers dropping out. It was, and that behaviour has its own rules and its own pitfalls, covered in distributive conditional types. The built-in Exclude and Extract from the utility types lesson are written exactly this way.
About the video
Kyle Cook’s video is a 25-minute tour of advanced TypeScript, and the embed starts at 0:33, where he begins with extends as a generic constraint and then builds up the T extends U ? X : Y form. That first stretch, up to about 9:31, is this lesson. After that he moves on to infer and then template literal types, which are the next lessons in this group, so you can keep watching or come back to those parts later. The two links below are single-topic alternatives: Jack Herrington’s shows a callback-or-promise return type and compares it with overloads, and Nicos Tsourektsidis’s is a longer walk through conditional types on their own.
Check yourself
What does `IsString<"hello">` resolve to, given `type IsString<T> = T extends string ? true : false`, and why?
`true`. The literal type `"hello"` is assignable to `string`, so the condition holds and the true branch is chosen. `extends` asks whether every value of the left type is also a value of the right type.
Given `type HasId<T> = T extends { id: number } ? true : false`, why is `HasId<{ id: number; name: string }>` true when that type never declared any relationship to `{ id: number }`?
In a conditional type `extends` is a structural assignability check. `{ id: number; name: string }` extends `{ id: number }` because it has every property the right side requires, even though no class or interface ever declared that relationship.
Inside `function wrap<T>(x: T): T extends string ? string[] : T`, why can't the compiler tell which branch the return value should match?
Inside the body `T` is still a type parameter, so the conditional is deferred and has no concrete branch yet. Returning `[x]` or `x` doesn't match the unresolved conditional type, which is why such bodies typically use an assertion or the function is written with overloads.
How would you write a type that maps `string` to `"text"`, `number` to `"num"` and anything else to `"other"`?
Nest the conditionals in the false branch: `T extends string ? "text" : T extends number ? "num" : "other"`. Each condition is tried only if the ones before it failed, like a chain of `else if` statements.
When would a plain generic constraint be enough and a conditional type be unnecessary?
When the output type doesn't change shape with the input. A constraint like `T extends { id: number }` limits what callers may pass; a conditional is only needed when the result must differ depending on what was passed.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.