Sub topic 3
Combining Defaults with Constraints in TypeScript
Assume you know basic generic functions, object types, unions, keyof, and indexed access types.
Combining defaults with constraints, and the ordering rules
A type parameter can have both a constraint and a default:
type Box<T extends string | number = string> = {
value: T;
};
const text: Box = { value: "hello" };
const count: Box<number> = { value: 42 };
// const flag: Box<boolean> = { value: true };
// Error: boolean does not satisfy the constraintThe constraint limits valid arguments. The default supplies a type when the caller omits the argument. A default must satisfy its constraint.
Required type parameters must come before parameters with defaults:
type Pair<A, B = A[]> = {
first: A;
second: B;
};This is valid because A is required and B has a default. A required parameter after a default is invalid.
Inference, defaults, and constraints: which one wins
TypeScript usually infers a type from the function arguments. If inference produces a type, that inferred type takes precedence over the default. The constraint then checks whether the inferred type is allowed.
If there is no inference candidate, TypeScript uses the default:
function parse<T = unknown>(text: string): T {
return JSON.parse(text) as T;
}
const a = parse("42"); // unknown: no inference candidate
const b = parse<number>("42"); // number: explicit argumentA constraint is not a fallback type. It describes the permitted range of types:
function sizeOf<T extends { length: number }>(value: T): number {
return value.length;
}
sizeOf("abc"); // T is inferred as string
sizeOf([1, 2, 3]); // T is inferred as number[]Designing reusable APIs with both features
Combine a constrained model with a computed default when the common case follows a predictable shape:
interface Repository<
T extends { id: string },
TCreate = Omit<T, "id">
> {
create(input: TCreate): T;
findById(id: string): T | undefined;
}For a Book type, callers can write Repository<Book>. The default makes create accept the book fields without id, while the constraint guarantees every stored value has an id.
Exercise
In type Result<T extends string | number = string> = T, what type does Result use, and is Result<boolean> valid?
Show answer
Result uses the default string. Result<boolean> is invalid because boolean violates the constraint.