Understanding Generics <T> in Typescript
You know that moment when you’re writing a function, and it hits you—“Wait, I need this same logic for strings, for users, for settings…”? And you start duplicating code like a photocopier on overdrive? Yeah. That’s the sound of tech debt knocking. Generics in TypeScript? They’re the quiet fix. The “write once, work everywhere” backbone for smart, type-safe code. No hacks. No any
loopholes.
Let’s dive in.
Imagine you’re building a vending machine. You want it to handle snacks, drinks, maybe even tiny plushies. You could build a separate machine for each. Or—genius move—you design one that adapts. Slot in a chip? Fine. A soda? Cool. A rubber duck? Why not. That’s generics. A template that doesn’t lock you into one type.
So, what’s the deal with <T>
? That weird angle-bracket thing?
Think of T
as a placeholder. A stand-in. Like “insert your type here.” It’s not a real type—yet. It’s a promise: “Hey, when you call me, tell me what you’re working with, and I’ll adjust.”
function wrapInBox<T>(item: T): { content: T } {
return { content: item };
}
See that <T>
? It’s not syntax fluff. It’s the key. Now you can: