Sub topic 5
Conditional types: choosing a type with extends
What a conditional type is
A conditional type picks one of two types based on a check. It uses the same shape as the ternary operator in JavaScript, but it runs at the type level:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<number>; // falseRead T extends string ? true : false as "if T is assignable to string, the result is true. Otherwise it is false."
This chapter assumes you know object types, unions, function types, and generics with constraints. It also assumes you have seen keyof and indexed access types such as T[K] from earlier chapters.
The extends check means assignability
Inside a conditional type, extends does not mean class inheritance. It asks whether every value of the left type could be used where the right type is expected. This is the same assignability rule TypeScript uses for function arguments and variable assignments.
type IsString<T> = T extends string ? true : false;
type C = IsString<"a" | "b">; // true (see the distribution section)
type D = IsString<string>; // true
type E = IsString<unknown>; // false
type F = IsString<never>; // never (see the edge cases section)A few results follow from assignability:
- A string literal type such as
"hello"is assignable tostring, so it takes the true branch. stringis not assignable to"hello", sostring extends "hello"is false.- An object with extra properties is assignable to an object with fewer properties.
type HasId<T> = T extends { id: number } ? "yes" : "no";
type G = HasId<{ id: number; name: string }>; // "yes"
type H = HasId<{ name: string }>; // "no"
type I = HasId<{ id: string }>; // "no"G is "yes" even though the object has an extra name property. Assignability allows extra properties here because the check compares types, not fresh object literals.
How TypeScript evaluates the check
When TypeScript sees a conditional type with a concrete type, it resolves it right away. When the checked type is still a generic parameter, the conditional type stays unresolved (deferred) until the parameter is known.
function describe<T>(value: T): T extends string ? "text" : "other" {
// Inside the function, T is unknown, so the conditional is deferred.
// TypeScript will not let you return "text" or "other" without a cast.
return (typeof value === "string" ? "text" : "other") as any;
}
const x = describe("hi"); // type: "text"
const y = describe(42); // type: "other"Deferral is why a function that returns a conditional type usually needs a type assertion in its body. TypeScript cannot prove that the runtime branch matches the type-level branch. The caller still gets the precise type, so the assertion is a contained trade-off. Keep it inside the function and keep the conditional type small.
Choosing between more than two types
A conditional type has only two branches, but the false branch can hold another conditional type. Chaining them works like an if / else if / else ladder:
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 T1 = TypeName<string>; // "string"
type T2 = TypeName<() => void>; // "function"
type T3 = TypeName<string[]>; // "object"
type T4 = TypeName<string | 1>; // "string" | "number"Order matters because TypeScript stops at the first check that passes. Put the most specific checks first. T4 returns a union because the check distributes over each member of the union, which is covered below.
Using the checked type in a branch
In the true branch, TypeScript narrows T to the part that satisfied the check. This lets you use T where the constraint matters:
type Unwrap<T> = T extends { value: infer V } ? V : T;
type U1 = Unwrap<{ value: number }>; // number
type U2 = Unwrap<string>; // stringThis example uses infer, which gets its own chapter. For now, treat infer V as "name whatever type sits in this position." The point here is that the false branch can return T unchanged, which makes the conditional act as an optional unwrapper.
Conditional types with constraints
A conditional type often replaces overloads. Suppose a function returns a string for string input and a number for number input:
type Result<T extends string | number> =
T extends string ? string[] : number;
function parse<T extends string | number>(input: T): Result<T> {
if (typeof input === "string") {
return input.split(",") as Result<T>;
}
return (input * 2) as Result<T>;
}
const parts = parse("a,b,c"); // string[]
const doubled = parse(21); // numberThe constraint T extends string | number rejects other argument types at the call site. The conditional type then maps each allowed input to its output type.
// parse(true); // Error: Argument of type 'boolean' is not assignableOverloads are often clearer for two or three cases and give better error messages. Conditional return types fit better when the mapping is regular and spans many input types, or when the result feeds other type-level code.
Conditional types inside object types
You can use a conditional type for a single property, which makes one field depend on another type parameter:
type ApiResponse<T, E = never> = {
data: T;
error: [E] extends [never] ? null : E;
};
type Ok = ApiResponse<string>;
// { data: string; error: null }
type Failed = ApiResponse<string, Error>;
// { data: string; error: Error }[E] extends [never] wraps both sides in a tuple. This avoids a problem with never that the edge cases chapter covers. For now, notice that it lets E = never mean "no error type."
Common errors
These are the mistakes that most often surprise people who are new to conditional types.
- Expecting a conditional type to resolve inside a generic function. The type is deferred while
Tis unknown. You cannot assign a concrete value to it without an assertion. - Reading
extendsas inheritance. It checks assignability, so structural matches count, and extra properties do not break the check. - Checking the wrong direction.
T extends stringasks whetherTfits instring.string extends Tasks the opposite. The two give different answers for literals and unions. - Forgetting that a union may distribute.
IsString<string | number>does not return a single boolean. It returnsboolean, the union oftrueandfalse. - Putting broad checks before narrow ones in a chain. A first check against
objectwould swallow arrays and functions before later checks see them.
type IsString<T> = T extends string ? true : false;
type Q1 = IsString<string | number>; // boolean (true | false)Writing your own helper
A short helper shows the full workflow. The goal is a type that keeps only the string members of a union:
type OnlyStrings<T> = T extends string ? T : never;
type Mixed = "a" | "b" | 1 | true;
type Strings = OnlyStrings<Mixed>; // "a" | "b"The true branch returns T itself, and the false branch returns never. Because never disappears from a union, the result keeps only the members that passed the check. This is the idea behind the built-in Extract utility type. You will rebuild it in a later chapter.
You can also test your helpers without extra tooling by assigning values to the expected type:
type OnlyStrings<T> = T extends string ? T : never;
const ok: OnlyStrings<"a" | 1> = "a";
// const bad: OnlyStrings<"a" | 1> = 1; // Error: Type 'number' is not assignable to type '"a"'Summary of the model
| Piece | Meaning |
|---|---|
| `T extends U` | Is `T` assignable to `U`? |
| `? X : Y` | Result is `X` if yes, `Y` if no |
| Concrete `T` | Resolved immediately |
| Generic `T` | Deferred until the type argument is known |
| Chained false branches | Ladder of checks, first match wins |
| `never` in a branch | Removes that member from a union result |
Exercise
Write a conditional type IsArray<T> that returns true for any array type and false otherwise. What do IsArray<number[]> and IsArray<string> return?
Show answer
type IsArray<T> = T extends any[] ? true : false; gives IsArray<number[]> = true and IsArray<string> = false. readonly string[] is not assignable to any[], so to include readonly arrays use T extends readonly any[] ? true : false.
Exercise
Given type Describe<T> = T extends string ? "text" : T extends number ? "numeric" : "other";, what is Describe<string | boolean>, and why?
Show answer
"text" | "other". The check distributes over the union, so string gives "text" and boolean (which is true | false) gives "other" for each member. The union of "text", "other" and "other" collapses to "text" | "other".