Generic constraints
Concept and syntax
A constraint T extends Shape permits type arguments assignable to Shape and allows the implementation to use its guaranteed members. It does not replace T with Shape; the function can still return the original subtype. Constrain only the capability the algorithm needs.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function lengthOf<T extends {length:number}>(x:T){return x.length;}console.log(lengthOf("tea"),lengthOf([1,2]),lengthOf({length:7}));Expected output:
3 2 7Common mistake
Intentionally invalid; compile separately and do not execute.
function lengthOf<T extends {length:number}>(x:T){return x.length;}lengthOf(7);Expected diagnostic: TS2345. A number has no required length property. Pass a value meeting the constraint.
Practice and recap
Write a function constrained to objects with id:number.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic constraints — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function lengthOf<T extends {length:number}>(x:T){return x.length;}console.log(lengthOf("tea"),lengthOf([1,2]),lengthOf({length:7}));Which diagnostic and explanation match the rejected example under the lesson settings?
function lengthOf<T extends {length:number}>(x:T){return x.length;}lengthOf(7);