Sub topic 10
Inference, Defaults, and Constraints: Which One Wins
Assume you know basic TypeScript types, interfaces, unions, and generic functions such as identity<T>(value: T): T. This chapter focuses on what happens when a type parameter has both inference and a default, especially when it also has an extends constraint.
A generic type parameter can get its type from three places:
- An explicit type argument, such as
parse<number>(text). - Type inference from function arguments or context.
- A default type, if no type can be inferred.
A constraint does not usually provide the type. It limits which types are allowed.
function parse<T = unknown>(json: string): T {
return JSON.parse(json) as T;
}
const first = parse("42"); // T is unknown: the default applies
const second = parse<number>("42"); // T is number: the explicit argument wins
console.log(first, second);In the first call, the parameter json has type string, but it does not contain T. TypeScript has no inference candidate for T, so it uses the default unknown. In the second call, the explicit type argument sets T to number.
The order of decisions
For most generic calls, use this model:
| Source of the type | When it applies | Example |
|---|---|---|
| Explicit type argument | The caller supplies a type | `parse<number>("42")` |
| Inferred type | Arguments or context provide evidence | `identity("Ada")` |
| Default type | No type can be inferred | `parse("42")` |
Inference normally beats a default. Consider a function whose argument contains T:
function wrap<T = string>(value: T): T[] {
return [value];
}
const words = wrap("hello"); // T is string, inferred from the argument
const count = wrap(10); // T is number, inferred from the argument
const empty = wrap<string>("hello"); // T is explicitly string
console.log(words, count, empty);The default string is used only when inference has no candidate. In this example, every call supplies an argument that determines T, so the default does not change the result.
Constraints check candidates
A constraint says what an inferred or explicit type must support. It does not force TypeScript to choose the constraint itself.
function longest<T extends { length: number }>(
a: T,
b: T
): T {
return a.length >= b.length ? a : b;
}
const arrayResult = longest([1, 2, 3], [4, 5]);
const textResult = longest("ab", "abcd");
console.log(arrayResult, textResult);The constraint lets the function body read .length. Arrays and strings satisfy the constraint, so they can be used. The inferred T remains related to the actual arguments rather than becoming { length: number }.
An explicit type argument must also satisfy the constraint:
function describe<T extends { id: number }>(item: T): number {
return item.id;
}
describe({ id: 7, name: "Ada" }); // T includes both id and name
// describe("Ada"); // Error: string has no numeric idA default on a constrained parameter follows the same rule. The default must satisfy the constraint.
interface Identified {
id: number;
}
function getId<T extends Identified = Identified>(item?: T): number {
return item?.id ?? 0;
}
const known = getId({ id: 12, label: "book" }); // T is inferred
const fallback = getId(); // T is Identified
console.log(known, fallback);When an object is passed, inference chooses the object's type. When no object is passed, the default Identified supplies T.
A constrained default and a dependent type
Defaults can depend on earlier type parameters. This is useful when an API has a common shape but still allows customization.
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>;
const created = books.create({ title: "TypeScript Guide" });
// T is Book, and TCreate defaults to { title: string }
console.log(created.title);Here, T must have an id string. Since TCreate is omitted, it defaults to Omit<T, "id">. The default is computed from the already chosen T.
One useful way to predict the result is to trace the dependencies:
Common mistakes
- Expecting a constraint to become the inferred type.
- Assuming a default overrides an argument-derived type.
- Giving a default that violates its constraint.
- Supplying a later type argument while omitting an earlier required one.
- Treating a cast such as
as Tas proof that runtime data really has typeT.
Exercise
For function f<T extends string | number = string>(value?: T): T | undefined, what type does f() use, and what type does f(123) use?
Show answer
f() uses the default string, so its result is string | undefined. f(123) infers T as number, so its result is number | undefined.