TypeScript Generic Constraints
A constraint states the minimum structure a generic input must provide. It lets the implementation use that structure while preserving extra information belonging to the caller’s actual type.
How it works
A summary helper needs a code but should not erase packet counts or desk metadata. T extends an object with code expresses that minimum requirement. The helper returns the original value alongside display text, retaining its precise type. This contract differs from inventing a new T: returning the received value is justified because the caller supplied it.
Run the code
Try in playground loads this source without running it. Choose Run when ready. The existing TypeScript 5.8.3 worker transpiles and executes one file; it does not perform full semantic type checking, load npm imports or provide DOM/Node APIs. Use the local compiler for the type contract.
For a full check, save the three downloads together in a new folder, run npm install, then npm run check. Use npm run build followed by npm start to execute the checked JavaScript with Node. The supplied project enables strict checking, indexed-access checks and exact optional properties.
Example
function summarize<T extends { code: string }>(value: T): { text: string; original: T } {
return { text: value.code.toUpperCase(), original: value };
}
const result = summarize({ code: "bn-2", packets: 7 });
console.log(result.text, result.original.packets);
Expected result
BN-2 7
The constraint permits reading code, and inference preserves packets in original. It does not require the object to have only a code property. If a helper only returns a string and never exposes the relationship again, accepting a simple code-bearing interface may be clearer than making it generic.