Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Type parameter
- A placeholder, such as T, for a type the caller supplies or the compiler infers.
- Bound or constraint
- What a type parameter must support: extends in TypeScript, a constraint in Go, a trait bound in Rust, a concept in C++.
- Instantiation
- A generic definition used with concrete type arguments. Rust monomorphization and C++ template specialization support concrete uses; optimization controls the emitted code.
- Parametric polymorphism
- One definition parameterized by types, using the operations its contract supports. Constraints and callbacks can make behavior depend on supported operations.
One definition parameterized by types
A generic definition introduces a type parameter such as T. The caller supplies a type, often inferred from its arguments, and the signature preserves relationships: a helper accepting a collection of T can return a T rather than discard the element type.
The body needs support for every operation it performs. A bound or constraint states required capabilities; a callback can instead supply an operation such as reading a comparison key. The type argument also affects defaults, ownership and arithmetic, so generic reuse still has a concrete contract.
TypeScript checks the generic body against its declared constraints. Type parameters are erased before execution; runtime decisions inspect values rather than ask which T was chosen.
01One function, many types
A type parameter stands for the caller’s type
A typed inventory report library selects a product record by a price callback, reads the first value of a price series and averages recorded quantities. These helpers are intended for callers with different record and numeric types. The supplied callers exercise a small set, so a helper must keep its generic contract as well as produce this report.
The inventory library needs a selection helper before it is connected to the report’s full records. These reduced numeric and string or callback-based calls check how one body selects a value for different caller types. Predict both results.
function largest<T>(items: T[], key: (item: T) => number): T {
return items.reduce((best, item) => (key(item) > key(best) ? item : best));
}
const prices = [3, 9, 4];
const fruits = [
{ name: "fig", price: 2 },
{ name: "pear", price: 5 }
];
console.log(
largest(prices, (price) => price),
largest(fruits, (fruit) => fruit.price).name
);
npx tsc --noEmit --strict --target ES2022 main.ts && node main.ts
Use the setup from the first reading for your language.
02Bounds and constraints
Each operation needs support from the type
A proposed library helper reads an extra property or compares values. Inspect the declared type requirements and the supplied caller before deciding whether that use is accepted.
function total<T>(items: T[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
console.log(total([{ price: 2 }, { price: 5 }]));
03An empty answer
A default value is not the same as no value
A price-series import can contain no observation, while a real first observation can be zero. These reduced first-value probes show what their return carriers keep or erase; predict the printed results.
function first<T>(items: T[]): T | undefined {
return items[0];
}
console.log(first([4, 7]), first<number>([]));
04Repair the typed inventory report
Keep the selected record, distinguish no price, then preserve the average
The first helper must return the original record with the highest quoted price; the callback tells it how to read a price without assuming a particular product shape. The first-value helper feeds a price-series report where an empty series means none and a genuine first price of 0 remains 0. The average helper formats integral quantity observations to two decimal places, including their fractional mean.
These are three library contracts used by the inventory report, with a complete supplied caller for each. Ties keep the earlier record. Empty and zero witnesses protect distinct meanings; fractional cases protect the arithmetic performed before formatting.
Repair the typed inventory report
A comparison in a generic body, an empty generic answer, then arithmetic in the type parameter.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?