Sub topic 1
Conditional types: choosing a type with extends
A conditional type picks one of two types based on a test. It is the base for the rest of this tutorial. infer is an extension of the conditional type, and every recursive type you will write later is a conditional type that refers to itself. This chapter covers the syntax, what the test means, how evaluation can be delayed, and the cases that surprise people.
Prerequisites
This chapter assumes you already know:
- Generics and type parameters, such as
type Box<T> = { value: T }. - Union types (
A | B), intersection types (A & B) and tuple types ([string, number]). - Mapped types and
keyofat a basic level. - How to write function type signatures, such as
(x: number) => string. - The basic syntax of template literal types, such as `
id_${string}`.
You do not need to know infer or recursive types yet. Later chapters introduce them.
The working model
A conditional type has this shape:
type Choose<T> = T extends U ? X : Y;TypeScript asks whether T is assignable to U. If it is, the result is X. If it is not, the result is Y. Here is a first example:
type IsString<T> = T extends string ? true : false;
type A = IsString<string>; // true
type B = IsString<'hello'>; // true
type C = IsString<number>; // false'hello' is assignable to string, so B is true. The word extends here does not mean class inheritance. It means "is assignable to", which is the same relation the compiler uses when you pass an argument to a function parameter.
It runs at compile time
A conditional type is not a runtime if. It exists only in the type system, and the compiler erases it before the code runs. You cannot branch on it in JavaScript. You can only use it to describe types, for example the type of a function's return value or the shape of an object.
The third arrow in the diagram matters in practice. If T is a type parameter that has not been replaced by a real type, the compiler cannot answer the question yet. It keeps the conditional type as it is and resolves it later, when someone supplies a concrete type.
Testing object shapes
The right-hand side of extends can be any type, not only a primitive. Object types test for the presence of properties:
type HasId<T> = T extends { id: number } ? true : false;
type U1 = HasId<{ id: 1; name: string }>; // true
type U2 = HasId<{ name: string }>; // falseU1 is true even though the type has an extra name property. Assignability allows extra properties on a type that is not a fresh object literal. The test asks "does it have at least this shape", not "does it have exactly this shape".
Using the checked type inside a branch
Inside the true branch, TypeScript knows more about T. It treats T as also satisfying the type on the right of extends. This lets you use features that only exist on that type:
type Flatten<T> = T extends unknown[] ? T[number] : T;
type F1 = Flatten<string[]>; // string
type F2 = Flatten<number[][]>; // number[]
type F3 = Flatten<number>; // numberT[number] is only legal on array-like types. It compiles in the true branch because the compiler knows T is an array there. Flatten removes only one level of nesting, so F2 is number[], not number. Removing every level needs recursion, which comes later.
Chaining conditions
The false branch can hold another conditional type. This gives you something like an else if chain:
type TypeName<T> =
T extends string ? 'string' :
T extends number ? 'number' :
T extends boolean ? 'boolean' :
T extends undefined ? 'undefined' :
T extends (...args: any[]) => any ? 'function' :
'object';
type N1 = TypeName<'x'>; // 'string'
type N2 = TypeName<() => void>; // 'function'
type N3 = TypeName<{ a: 1 }>; // 'object'TypeScript checks the conditions from top to bottom and stops at the first one that matches. Put the most specific checks first. If you test T extends object before the function check, functions match the earlier test and never reach the later one.
Return types that depend on an argument
A common use is a function whose return type depends on the type of an argument:
type Result<T extends boolean> = T extends true ? string : number;
function getValue<T extends boolean>(flag: T): Result<T> {
return (flag ? 'yes' : 42) as Result<T>;
}
const a = getValue(true); // string
const b = getValue(false); // numberCallers get the precise type. The as Result<T> cast is needed inside the function body because the compiler cannot prove that a runtime flag ? ... : ... matches a conditional type that depends on T. The compiler checks the signature for callers but does not follow your runtime logic. If you write the wrong value in the body, the cast hides the mistake. For a function with only two or three cases, overloads are often safer.
Special cases to know
A few inputs do not follow the simple "yes or no" model. This chapter only names them. The next chapter explains the mechanism behind the union and never cases.
| Input as the checked type | Result for `IsString<...>` | Why | Column | Column |
|---|---|---|---|---|
| `string \ | number` | `boolean` (that is, `true \ | false`) | The test runs on each union member separately and the results are joined. |
| `never` | `never` | There are no members to test, so the joined result is empty. | ||
| `any` | `boolean` | `any` is treated as possibly matching, so the result is both branches combined. | ||
| `unknown` | `false` | `unknown` is not assignable to `string`. |
Here is the union case in code:
type IsString<T> = T extends string ? true : false;
type M = IsString<string | number>; // boolean
type N = IsString<never>; // never
type O = IsString<any>; // boolean
type P = IsString<unknown>; // falseIf you wanted IsString<string | number> to be false, because the union as a whole is not a string, you need to change how the test is written. That fix is the subject of the next chapter.
Assignability is not equality
Because extends tests assignability, the result can differ from what you expect when the types are related but not the same:
type IsNumber<T> = T extends number ? true : false;
type L1 = IsNumber<1>; // true, the literal 1 is a number
type L2 = IsNumber<number>; // trueReadonly arrays are a common trap. A readonly string[] is not assignable to string[], because a mutable array type allows operations that a readonly one forbids:
type IsArray<T> = T extends unknown[] ? true : false;
type IsAnyArray<T> = T extends readonly unknown[] ? true : false;
type R1 = IsArray<readonly string[]>; // false
type R2 = IsAnyArray<readonly string[]>; // true
type R3 = IsAnyArray<string[]>; // truereadonly unknown[] accepts both readonly and mutable arrays, so it is the safer test when you want "any array". The same applies to readonly tuples, which matter again in the chapters on tuple recursion.
Filtering with never
Returning never from a branch removes that member from a union, because never disappears when joined with other types. The built-in Exclude and Extract use this:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type Letters = 'a' | 'b' | 'c';
type NoA = MyExclude<Letters, 'a'>; // 'b' | 'c'
type OnlyAB = MyExtract<Letters, 'a' | 'b'>; // 'a' | 'b'These work because the test runs on 'a', 'b' and 'c' one at a time. Each member that matches U becomes never in MyExclude and vanishes. Without that per-member behavior, MyExclude<Letters, 'a'> would test the whole union against 'a', fail, and return Letters unchanged. The next chapter explains exactly when this per-member behavior applies and how to switch it off.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `IsArray<readonly string[]>` returns `false`. | A mutable array type on the right of `extends`. | Test against `readonly unknown[]`. |
| The result is a union of both branches, such as `boolean`. | The checked type is a union or `any`. | Decide whether you want per-member results. See the next chapter. |
| The result is `never` for a `never` input. | `never` has no members to test. | Handle `never` explicitly if you need a different answer. |
| An early branch always wins. | A general test comes before a specific one. | Order the chain from most specific to most general. |
| A hover shows the unresolved `T extends U ? X : Y`. | The type parameter has not been given a concrete type. | Hover on a use site with real types, or check the call site. |
| Property access fails in a branch. | The branch's guarantee is weaker than you assumed. | Check what the `extends` clause promises about `T`. |
Summary of the model
T extends U ? X : YreturnsXifTis assignable toU, andYotherwise.- The test is assignability, so extra properties, literal types and subtypes all pass.
- Inside the true branch, the compiler treats
Tas also satisfyingU. - Branches can nest to form chains. Order them from most specific to most general.
- A conditional type on a generic parameter stays unresolved until the parameter is known.
- Unions,
neverandanydo not follow the simple yes/no model.
Exercise
Write a type IsFunction<T> that is true when T is any function type and false otherwise. What do IsFunction<() => void>, IsFunction<(a: number) => string> and IsFunction<string> return?
Show answer
type IsFunction<T> = T extends (...args: any[]) => any ? true : false; The first two return true because any function type is assignable to (...args: any[]) => any. IsFunction<string> returns false.
Exercise
Given type IsArray<T> = T extends unknown[] ? true : false;, what is IsArray<readonly number[]>, and how do you change the type so that it returns true?
Show answer
It is false, because readonly number[] is not assignable to the mutable unknown[]. Change the right side of extends to readonly unknown[], which accepts both readonly and mutable arrays.
Exercise
Write OrNever<T, U> that returns T when T is assignable to U and never otherwise. Then say what OrNever<'a' | 1, string> gives, and which concept from the "Special cases" table explains it.
Show answer
type OrNever<T, U> = T extends U ? T : never; The result for 'a' | 1 is 'a'. The test runs on 'a' and 1 separately: 'a' matches and is kept, and 1 becomes never and disappears from the union. This is the per-member behavior of unions, which the next chapter covers in detail.