Sub topic 10
Inference, defaults, and constraints: which one wins
This chapter assumes you can write generic functions with extends constraints and can declare default type parameters on interfaces and aliases. Both features were covered in the earlier chapters. Here you will learn to predict which type TypeScript picks for a type parameter when an inferred type, a default, and a constraint are all available.
The three sources of a type argument
For each type parameter at a call site, TypeScript works from three sources:
- An explicit type argument that you write, such as
parse<number>("1"). - Inference candidates collected from the arguments (and sometimes from the type the result is assigned to).
- The parameter's declared default, then its constraint, when there are no candidates.
The constraint has a second job. It is also a check that is applied to whatever type was chosen. Keeping the two roles of the constraint apart (fallback and validator) removes most of the confusion.
The sections below take each branch in turn.
Inferred types beat defaults
A default is not a preference that competes with inference. It is only consulted when inference has nothing to offer.
function wrap<T = string>(value?: T): { value: T | undefined } {
return { value };
}
const a = wrap(42); // T inferred as number; the default is ignored
const b = wrap(); // no candidates, so T = string (the default)
const c = wrap<boolean>(); // explicit argument, T = booleanIn wrap(42), the argument 42 is a candidate for T, so the result is { value: number | undefined }. The default string plays no part. Writing T = string does not stop callers from passing numbers.
Defaults also supply the type when you write a generic type without arguments. That includes classes, whose constructor may offer no candidates:
class Box<T = string> {
constructor(public value?: T) {}
}
const x = new Box(); // Box<string>: no candidates, so the default applies
const y = new Box(10); // Box<number>: inferred from the constructor argument
const z: Box = new Box(); // a bare Box in a type position means Box<string>Interfaces and type aliases never infer from a bare annotation like const a: ApiResponse = {}. They use the defaults for every omitted argument.
The constraint as a fallback
If there are no candidates and no default, the constraint becomes the inferred type. Without a constraint the fallback is unknown.
function pick<T extends string | number>(...items: T[]): T[] {
return items;
}
const none = pick(); // T = string | number (the constraint)
const some = pick("a", "b"); // T = "a" | "b"Adding a default changes only the no-candidate case:
function pickStrings<T extends string | number = string>(...items: T[]): T[] {
return items;
}
const d = pickStrings(); // T = string: the default wins over the constraint
const e = pickStrings(1, 2); // T = 1 | 2: candidates win over bothThe default must satisfy the constraint, so it is always a valid choice. It is usually narrower than the constraint, which makes it a good "most common case" type.
The constraint as a validator
After TypeScript picks a type, it checks that the type satisfies the constraint. What happens when the check fails depends on where the type came from.
For an inferred type, TypeScript abandons the failing candidate and uses the constraint as T instead. The argument is then checked against the constraint, which produces the error you see:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// longest(10, 20);
// Error: Argument of type 'number' is not assignable to parameter
// of type '{ length: number; }'.The message names the constraint type, not number. When you see a parameter type that looks like your constraint, the inferred candidate probably failed the check.
For an explicit type argument, there is no fallback. longest<number>(10, 20) reports that number does not satisfy the constraint { length: number }.
A failed constraint does not trigger the default. The default is for the no-candidate case only, so a default will never rescue a bad argument.
Constraints shape how literals are inferred
The constraint also affects how specific the inferred type is. Without a constraint, TypeScript usually widens a literal candidate ("a" becomes string) when T sits inside another type. A constraint that includes a primitive type tells TypeScript you want literals kept.
function box<T>(value: T): { value: T } {
return { value };
}
function boxLiteral<T extends string>(value: T): { value: T } {
return { value };
}
const p = box("a"); // { value: string }
const q = boxLiteral("a"); // { value: "a" }This is why K extends keyof T yields the exact key and T[K] the exact property type. A constraint can be a way to ask for a more precise inference, not only a restriction on what is allowed.
An object candidate keeps all its properties too. With T extends { id: number }, calling with { id: 1, tag: "x" } infers T as { id: number; tag: string }, not { id: number }. The constraint is a lower bound on what T must offer, and T can be wider.
Explicit type arguments turn inference off
TypeScript has no partial inference. If you write any type arguments at the call site, it does not infer the rest. The remaining parameters take their defaults, or the call is an error if a remaining parameter has no default.
function convert<TIn, TOut = string>(
input: TIn,
fn: (x: TIn) => TOut
): TOut {
return fn(input);
}
const r1 = convert(1, (n) => n + 1); // TIn = number, TOut = number (both inferred)
const r2 = convert<number>(1, (n) => String(n)); // TOut = string (the default)
// const r3 = convert<number>(1, (n) => n + 1);
// Error: number is not assignable to string, because TOut was fixed to its defaultThe third call fails because naming TIn explicitly stopped inference of TOut, and the default string was used instead. If TOut had no default, convert<number>(...) would fail with "Expected 2 type arguments, but got 1."
This makes the order of type parameters part of your API. Put the parameters callers are likely to name first, and give later ones defaults that match common use.
Defaults on return-only type parameters
When T appears only in the return type, there are no argument candidates. TypeScript may still infer from the type the result is assigned to, which is called the contextual return type.
function parse<T = unknown>(json: string): T {
return JSON.parse(json) as T;
}
const u = parse("1"); // unknown: the default applies
const n: number = parse("1"); // T inferred from the annotation: number
const s = parse<string>('"hi"'); // explicit: stringReturn-type inference ranks below argument inference. It beats the default, because an assignment target is real information about what the caller wants. Nothing here checks the JSON at runtime, so a type argument on parse is a claim, not a guarantee. A function like this deserves a validation step in real code.
Summary of outcomes
The table lists the type each call gets, using the functions from this chapter.
| Call | Candidates | Result for the parameter | Why | Column |
|---|---|---|---|---|
| `wrap(42)` | `number` | `number` | Inference beats the default | |
| `wrap()` | none | `string` | Default used | |
| `pick()` | none | `string \ | number` | No default, so the constraint is used |
| `pickStrings()` | none | `string` | Default beats the constraint | |
| `longest(10, 20)` | `number` (fails) | `{ length: number }` | Candidate rejected, constraint used, then an argument error | |
| `convert<number>(1, fn)` | not inferred | `TOut = string` | Explicit arguments disable inference of the rest | |
| `const n: number = parse("1")` | `number` from context | `number` | Return-context inference beats the default |
Designing with the order of precedence
These rules suggest some practical guidance for API design.
- Give a default when a sensible value exists for the "no information" case, such as an error type of
Erroror a payload ofunknown. Do not give one just to silence errors. - Make the default the narrowest useful type. A default equal to the constraint adds little, because the fallback already gives that type when there is no default.
- Order parameters by how likely callers are to name them, and keep defaults last. Remember that naming one parameter freezes the later ones at their defaults.
- Prefer inference for function type parameters. Reserve defaults for interfaces, aliases, and classes, where inference is not available from a bare annotation.
- Use a constraint to keep literals when callers should get exact types back, as in
<K extends string>.
A default can refer to earlier parameters, which lets one input determine another when the caller says nothing:
interface Repository<T extends { id: string }, TCreate = Omit<T, "id">> {
create(input: TCreate): T;
findById(id: string): T | undefined;
}
interface Book {
id: string;
title: string;
}
declare const books: Repository<Book>; // create takes { title: string }
declare const drafts: Repository<Book, { title?: string }>; // caller overrides the default
const book = books.create({ title: "Dune" }); // BookCommon mistakes
- Expecting a default to apply when the argument does not satisfy the constraint. The default is only used when there are no candidates.
- Writing
T = stringand assuming callers cannot pass numbers. Any argument that gives a candidate overrides the default. - Naming one type argument and expecting the others to be inferred. They take their defaults, or the call is an error.
- Reading an error that shows the constraint type as the parameter type as a problem with the constraint. Look at the argument you passed, which probably failed to satisfy it.
- Forgetting that a call with no information at all returns the constraint (or
unknown). An emptypick()returns(string | number)[], which may be wider than you intended.
Exercise
Given function make<T extends object = { id: number }>(...items: T[]): T[], what is the type argument for make(), for make({ name: "a" }), and for make<{ id: number; ok: boolean }>({ id: 1 })? Say which call is an error and why.
Show answer
make() has no candidates, so the default applies: T = { id: number }. make({ name: "a" }) has a candidate, so inference wins over the default and T = { name: string }, which satisfies object. The third call is an error. The explicit T is { id: number; ok: boolean }, and the argument { id: 1 } lacks the required ok property. Explicit arguments are never replaced by inference.
Exercise
You write function request<TBody, TResult = unknown>(body: TBody, handler: (b: TBody) => TResult): TResult. A caller writes request<string>("x", (s) => s.length). Does it compile? Explain, and give two ways to fix the call.
Show answer
It does not compile. Naming TBody explicitly turns off inference for TResult, so TResult takes its default unknown. That default is not the problem here, because a callback returning number is assignable to a function returning unknown, and the call compiles but returns unknown. If the caller wants a number result, the fix is to write both arguments, request<string, number>(...), or to omit all type arguments and let TBody and TResult be inferred (request("x", (s) => s.length)), which gives number. Another option is to change the default to a more useful type or remove it so that request<string> is rejected.