Sub topic 5
Conditional types: choosing a type with extends
This chapter assumes you know basic TypeScript types, generics with constraints, and type aliases. A conditional type picks one of two types based on a check. The syntax is T extends U ? X : Y. If T is assignable to U, the result is X. Otherwise, the result is Y.
The check is assignability
The extends in a conditional type asks whether one type can be used wherever another is expected. It does not test for exact equality. A wider object type with extra properties still passes a check against a narrower one.
type HasId<T> = T extends { id: number } ? "yes" : "no";
type A = HasId<{ id: number; name: string }>; // "yes"
type B = HasId<{ name: string }>; // "no"The first object has an id and also has other properties, so it is assignable to { id: number }. The check passes.
Chaining conditions
You can nest conditional types to handle several cases in order. The first matching branch wins.
type Describe<T> = T extends string
? "text"
: T extends number
? "count"
: "other";
type D1 = Describe<"hi">; // "text"
type D2 = Describe<42>; // "count"
type D3 = Describe<boolean>; // "other"Extracting types with infer
The infer keyword declares a type variable inside the extends clause. TypeScript fills it in when the check matches, and you can use it in the true branch. This is how the built-in ReturnType works.
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type R1 = MyReturnType<() => Promise<string>>; // Promise<string>
type R2 = MyReturnType<(x: number) => boolean>; // boolean
type R3 = MyReturnType<string>; // neverThe never in the false branch means "no match." Returning never is a common way to signal that a type has no answer.
Common errors
- Distribution surprises. When the checked type is a naked type parameter and it receives a union, TypeScript applies the conditional to each member separately. Wrapping the parameter in a tuple, as in
[T] extends [U], stops this. - Checking the wrong direction.
T extends stringasks whetherTfits insidestring. Writingstring extends Tasks the reverse question, which usually gives a different result. - Expecting exact matches.
{ id: number; name: string }extends{ id: number }, so a check meant to reject extra properties will not behave as you expect. - Leaving
anyunexamined. IfTisany, a conditional type often returns a union of both branches.
> The next chapter covers how a union input splits across the branches.
Exercise
Exercise
What does IsArray<string[]> return if IsArray is defined as type IsArray<T> = T extends unknown[] ? true : false?
Show answer
true, because string[] is assignable to unknown[].