bhylu.com

Advertisements

TypeScript Generics

A generic parameter preserves a relationship between input and output types. Use it when callers supply different types but the function should keep each caller’s specific information.

How it works

The first-item helper works with numbers and labels. Returning unknown would force every caller to validate its own known input again; returning any would discard the relationship entirely. T connects the element type to the result. Because an array can be empty, the return also includes undefined. Generics do not justify promising a value that the runtime may not find.

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

lesson.ts

function first<T>(items: readonly T[]): T | undefined { return items[0]; }
const packetCount = first([5, 8]);
const label = first(["Bean", "Pea"]);
console.log(packetCount ?? 0);
console.log(label?.toUpperCase() ?? "No label");

Expected result

5
BEAN

The numeric call retains number, while the textual call retains string. Both callers handle absence. A generic parameter used only once in a signature often adds little: check whether it really connects two parts of the contract or merely makes the declaration harder to read.