Sub topic 11
Conditional Types
This chapter assumes you can write generic functions and type aliases with type parameters, and that you know extends constraints and union types. A conditional type lets a type alias choose between two types based on a test, in the same way an if expression chooses between two values.
The Basic Form
A conditional type has this shape:
type Result = SomeType extends OtherType ? TrueBranch : FalseBranch;TypeScript checks whether SomeType is assignable to OtherType. If it is, the result is TrueBranch. If not, the result is FalseBranch. The check is always assignability, never strict equality. Conditional types become useful when the checked type is a type parameter:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<string>; // true
type C = IsString<number>; // false
type D = IsString<unknown>; // false"hello" is a string literal type, and it is assignable to string, so A is true. unknown is not assignable to string, so D is false.
Because the test is assignability, an object type with extra properties still passes:
type HasId<T> = T extends { id: number } ? "yes" : "no";
type E = HasId<{ id: 1; name: string }>; // "yes"
type F = HasId<{ name: string }>; // "no"How a Conditional Type Is Evaluated
TypeScript resolves a conditional type as soon as it has enough information. If the checked type is still an unresolved type parameter, the result stays unresolved until a concrete type is supplied.
The "deferred" path explains most of the confusing errors people hit with conditional types, covered later in this chapter.
Chaining Conditions
The false branch can hold another conditional type. This gives you an if / else-if / else chain:
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
T extends undefined ? "undefined" :
T extends (...args: never[]) => unknown ? "function" :
"object";
type T1 = TypeName<"x">; // "string"
type T2 = TypeName<() => void>; // "function"
type T3 = TypeName<string[]>; // "object"Order matters because the first matching test wins. Chains of more than three or four tests are hard to read and slow to check, so consider a lookup type (an object type indexed by key) instead.
Using the Checked Type in the True Branch
Inside the true branch, TypeScript treats T as if it also satisfies the tested type. You can therefore index into it without an error:
type MessageOf<T> = T extends { message: unknown } ? T["message"] : never;
interface Email {
message: string;
subject: string;
}
type M1 = MessageOf<Email>; // string
type M2 = MessageOf<number>; // neverWithout the conditional, T["message"] would be an error because T has no known message property. The conditional acts as a type-level guard.
Returning never from the false branch is a common choice. It means "this input has no valid answer", and never disappears from unions, which is useful for filtering.
Conditional Types Describe Return Types
A common use is a function whose return type depends on its argument type:
type Converted<T extends string | number> = T extends string ? number : string;
function convert<T extends string | number>(value: T): Converted<T> {
if (typeof value === "string") {
return Number(value) as Converted<T>;
}
return String(value) as Converted<T>;
}
const n = convert("42"); // number
const s = convert(42); // stringCallers get precise types. The assertions inside the function body are needed, and the next section explains why.
Deferred Conditional Types and Assertions
Inside a generic function, T is unknown, so TypeScript cannot choose a branch. It keeps the conditional type as is, and it will not let you assign a value to it:
type Pick1<T> = T extends string ? 1 : 2;
function bad<T>(_input: T): Pick1<T> {
// return 1; // Error: Type '1' is not assignable to type 'Pick1<T>'
return 1 as Pick1<T>;
}Even if you narrow _input with typeof, TypeScript does not connect that narrowing to the return type. Narrowing a value does not resolve a conditional type that mentions T. The usual options are:
- Use a type assertion, as in
convertabove. This is unchecked, so a mistake in the body will not be caught. - Declare overloads for the specific cases and keep one loosely typed implementation signature.
- Return a simpler type and let the caller supply the narrower one.
Treat these assertions as a boundary. Keep the conditional logic small and test the public signature with real calls.
Special Inputs: never, any, and unknown
Three types behave in surprising ways when passed to a conditional type.
type IsString<T> = T extends string ? true : false;
type R1 = IsString<any>; // boolean
type R2 = IsString<unknown>; // false
type R3 = IsString<never>; // neveranyis assignable in both directions, so TypeScript returns the union of both branches.true | falseisboolean.unknownis only assignable tounknownandany, so it falls to the false branch.neverproducesnever, notfalse. This happens because a bare type parameter in the checked position distributes over unions, andneveris the empty union. Distribution gets its own chapter, so for now treat it as a rule to remember.
If you want never to count as an ordinary input, wrap both sides of the test in tuples:
type IsStringStrict<T> = [T] extends [string] ? true : false;
type S1 = IsStringStrict<never>; // true
type S2 = IsStringStrict<string | number>; // false[never] is assignable to [string], so you get true. A union such as string | number is tested as a whole, so it is not assignable and you get false.
Built-in Conditional Types
Several utility types in the standard library are conditional types:
| Utility type | What it does | Example result | Column |
|---|---|---|---|
| `Exclude<T, U>` | Removes members of `T` that are assignable to `U` | `Exclude<"a" \ | "b", "a">` is `"b"` |
| `Extract<T, U>` | Keeps members of `T` that are assignable to `U` | `Extract<"a" \ | "b", "a">` is `"a"` |
| `NonNullable<T>` | Removes `null` and `undefined` from `T` | `NonNullable<string \ | null>` is `string` |
You can write the first two yourself:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type Letters = "a" | "b" | "c";
type WithoutA = MyExclude<Letters, "a">; // "b" | "c"
type OnlyA = MyExtract<Letters, "a">; // "a"Each union member is tested separately. Members that fail the test become never and vanish from the result.
Putting a Conditional Type in an API
Conditional types fit well where the shape of a result depends on the input type. This example models a result that is either a value or an error, depending on what the caller passes:
type Outcome<T> = T extends Error
? { ok: false; error: T }
: { ok: true; value: T };
type Good = Outcome<number>; // { ok: true; value: number }
type Bad = Outcome<RangeError>; // { ok: false; error: RangeError }A union such as Outcome<number | RangeError> produces a union of both shapes, which a caller can narrow with the ok field.
Common Mistakes
- Expecting equality.
T extends Utests assignability.IsString<"a">istrueeven though"a"andstringare different types. - Forgetting the tuple wrapper. If you want a union tested as one unit, write
[T] extends [U]. - Mutable versus readonly arrays.
readonly number[]is not assignable tonumber[], so a test written againstunknown[]fails for readonly arrays. - Trying to narrow a deferred type. Runtime checks inside a generic function do not resolve
Converted<T>. Use an assertion or overloads. - Deep chains. A long chain of nested conditions is hard to read and slows compilation. Prefer a lookup object type when the cases are fixed keys.
- Using a conditional type when a constraint is enough. If you only need to reject bad inputs, write
T extends Xin the type parameter list. A conditional type is for computing a new type, not for validating an argument.
Exercise
A teammate writes type IsArray<T> = T extends unknown[] ? true : false;. What does IsArray<readonly number[]> produce, and how do you change the definition so that both number[] and readonly number[] give true?
Show answer
It produces false, because a readonly array is not assignable to a mutable array type. Change the test to T extends readonly unknown[]. Both number[] and readonly number[] are assignable to readonly unknown[], so both give true.
Exercise
Given type IsString<T> = T extends string ? true : false;, why does IsString<never> give never instead of false, and which one-line change makes it give true?
Show answer
A bare type parameter in the checked position distributes over a union, and never is the empty union, so there are no members to test and the result is never. Wrapping both sides in tuples, [T] extends [string] ? true : false, tests the type as a whole. [never] is assignable to [string], so the result is true.