TypeScript · Lesson 29 of 42
Conditional types and infer
Choose a type with T extends U ? X : Y, see how it distributes over unions, and extract inner types such as array elements and promise results with infer.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to write types that make decisions, the way if makes decisions in code, and to pull pieces out of other types. This is the most advanced idea in the course so far, and it powers many of the utility types you already use. Take it slowly and read the examples twice.
The conditional type
A conditional type looks like the ternary operator, but works on types. It uses extends to ask: "is T assignable to U?"
type IsString<T> = T extends string ? true : false;
const a: IsString<"hello"> = true;
const b: IsString<42> = false;
console.log(a, b);true falseIf T is a string, the type is true; otherwise it is false. The compiler evaluates this at compile time, and the types vanish at run time. You can check the result by trying a wrong assignment, which reveals what the type is:
type IsString<T> = T extends string ? true : false;
const wrong: IsString<42> = true;example.ts(3,7): error TS2322: Type 'true' is not assignable to type 'false'.A more practical example: a function whose return type depends on its argument type.
type Name<T> = T extends number ? string : number;
function convert<T extends string | number>(value: T): Name<T> {
return (typeof value === "number" ? String(value) : Number(value)) as Name<T>;
}
const asText = convert(42);
const asNumber = convert("17");
console.log(asText.padStart(4, "0"), asNumber + 1);0042 18Notice the assertion inside convert. The compiler cannot prove that the branches match a conditional return type, so a cast is the usual price; this is one of the few places where an assertion is normal, because the signature, not the body, is the contract.
Distribution over unions
When the checked type is a naked type parameter (just T, not [T] or T[]), a union is split, the conditional runs on each member, and the results are united:
type ToArray<T> = T extends unknown ? T[] : never;
const x: ToArray<string | number> = ["a"];
const y: ToArray<string | number> = [1];
console.log(x, y);[ 'a' ] [ 1 ]ToArray<string | number> is string[] | number[], not (string | number)[]. Distribution is the behaviour behind Exclude and Extract, which are conditional types:
type MyExclude<T, U> = T extends U ? never : T;
type Letters = "a" | "b" | "c";
type WithoutA = MyExclude<Letters, "a">;
const letter: WithoutA = "b";
console.log(letter);bFor each member of Letters, if it extends "a" it becomes never (which disappears from a union), otherwise it stays. To turn distribution off, wrap both sides in square brackets: [T] extends [U] ? ... : ....
infer: capturing a piece
Inside the extends part of a conditional type, you can write infer Name to ask the compiler to work out a type and give it a name. This extracts the element type of an array:
type ElementOf<T> = T extends (infer U)[] ? U : T;
const a: ElementOf<string[]> = "text";
const b: ElementOf<number[]> = 5;
const c: ElementOf<boolean> = true;
console.log(a, b, c);text 5 trueRead it as: "if T is an array of something, call that something U and give me U; otherwise give me T unchanged". Here is a hand-written ReturnType:
type MyReturnType<F> = F extends (...args: never[]) => infer R ? R : never;
function makeUser() {
return { name: "Asha", age: 30 };
}
type User = MyReturnType<typeof makeUser>;
const user: User = { name: "Ben", age: 25 };
console.log(user);{ name: 'Ben', age: 25 }And a version that unwraps a promise, which is how Awaited is built:
type Unwrap<T> = T extends Promise<infer V> ? V : T;
const a: Unwrap<Promise<string>> = "done";
const b: Unwrap<number> = 7;
console.log(a, b);done 7A practical use
Conditional types and mapped types combine well. This picks out the keys of an object whose values are functions:
type MethodNames<T> = {
[K in keyof T]: T[K] extends (...args: never[]) => unknown ? K : never;
}[keyof T];
type Counter = { value: number; increment(): void; reset(): void };
type Names = MethodNames<Counter>;
const method: Names = "increment";
console.log(method);incrementThe trailing [keyof T] indexes the mapped type to collect its values into a union, dropping the nevers. This is a pattern worth recognising even if you do not write it often.
When to stop
Conditional types are powerful and easy to overuse. Types that take a long time to read are a cost for everyone who maintains the code. A good test: if a simple function overload, a union or a utility type does the job, use that. Save conditional types for libraries and for places where the alternative is repeating many near-identical types.
Common mistakes
Expecting runtime behaviour. A conditional type is resolved at compile time. It cannot look at an actual value.
Forgetting distribution. A naked T splits a union. If you need the union treated as a whole, wrap it in brackets.
Writing infer outside extends. infer is only allowed in the extends clause of a conditional type.
Overcomplicating. If two readers disagree about what a type means, rewrite it.
Exercise
Write IsArray<T> returning true or false, and test it with string, number[] and string | string[], noticing the distribution. Write FirstArg<F> that gets the type of a function's first parameter using infer. Write NonFunctionKeys<T>, the opposite of MethodNames, and test it on an object type with both data and methods.
Next: Template literal types.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.