TypeScript Generics and Advanced Type Operators
Generic constraints — extends in type parameters
A constraint specifies what a type argument must satisfy, permitting operations justified by that contract. Unlike a parameter typed only as the constraint, a generic can retain additional properties of the actual argument. A constraint does not create a runtime check. Returning an arbitrary value that merely meets the constraint is not generally enough for a return type of T. Example output: "7 draft". Local strict TypeScript 5.8.3 / ES2022 baseline. The type construct itself is erased; the logged value illustrates a checked use, not runtime type validation.
Formal Syntax & Structure
typescript syntaxtypescript
function read<T extends { id: number }>(value: T): number { return value.id; }Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| T | constrained type parameter | Must be assignable to the declared bound. |
Working Example
Example Snippettypescript
function keep<T extends { id: number }>(value: T): T { return value; }const record = keep({ id: 7, label: "draft" });console.log(record.id, record.label);