🧭Generics
Also known as Generic Type, Generic Function, Type Parameter
Code written once that works with many types. A stand-in like T fills in.
Think of it like
Think of it like a lunch box that fits any food. Whatever you pack is what you get back.
Example
Lucy writes first<T> to get the first item of a list. Given numbers it gives back a number; given names it gives back a string.
Why it matters
Without generics you write the same list code for each type, or give up type checks. Generics avoid both.
Definition
Example code
typescript
function first<T>(items: T[]): T {
return items[0];
}
const n: number = first([1, 2, 3]); // 1Common mistake
Key takeaways
- 1One code, many types. Written once.
- 2A stand-in type. Often called T.
- 3Still checked. T becomes the real type.