The problem generics solve
You often want a function that works for any type while still relating its inputs and outputs. Without generics you would lose type information or copy the function for each type.
Type parameters
A generic introduces a type parameter, often named T, that stands in for a real type chosen at the call site. An identity function takes a T and returns a T, so passing a number returns a number, not a vague any.
Inference at the call site
You rarely write the type argument by hand. TypeScript infers T from the values you pass. Calling identity with a string sets T to string automatically.
Constraints
A generic can be limited with extends so it only accepts types meeting a shape. A function that reads a length can constrain T to types that have a length property, rejecting values that lack it.
Why it matters
- One implementation serves many types with no loss of safety.
- The relationship between input and output stays visible to the checker.
- Containers like arrays, promises, and maps are generic for exactly this reason.
Key idea
Generics carry type information through a reusable function so one definition stays precise for every concrete type.