Generics

Generics: A generic is like a printed form with blank boxes left open — a form labeled 'List' doesn't say what kind of list yet; the person using it fills in 'Number List' or 'Na

A generic is like a printed form with blank boxes left open — a form labeled 'List' doesn't say what kind of list yet; the person using it fills in 'Number List' or 'Name List' to decide. So instead of printing a separate form for every list type (one function for numbers, another for names), why not just have one fill-in-the-blank template? Because rewriting the same logic (sorting, filtering, appending) for every single type means both code duplication and a maintenance nightmare — Java's `List ` already provided this fill-in-the-blank idea, and TypeScript's generics carry the exact same concept forward. The concrete QA payoff: a single generic function like `function getFirst (items: T[]): T` works on a list of test cases, a list of users, and a list of error messages alike, returning the correct type every time — without generics you'd either lose type safety with `any` or be forced to write a separate function for every list type.

Java generics: ArrayList , Map . TypeScript is the same: Array , Map . Function generics: function identity (x: T): T. Already familiar from Java — just slightly different syntax.

function identity (value: T): T — T is determined at call time, not magic

— forces T to have a specific shape

Box , Box , Box — same class, different types, type safety maintained

Order the steps of designing a generic function:

Define type parameter with

Constrain with T extends if needed

Use T in parameter and return type

TypeScript infers T at call time

In function findMax (items: T[]): T, what happens with findMax([{ name: "test" }])?

Compile error — T doesn't satisfy the { value: number } constraint

Works — TypeScript accepts value as undefined

T relaxes to extends any