Lesson 169 of 1596
TypeScript Generics
Generics let a function work for many types while keeping type safety. The syntax looks scary and the concept is simple.
Creators · AI-Assisted Coding · ~27 min read
A Function, for Any Type
A generic is a placeholder that TypeScript fills in based on how you call the function. One `identity` works for strings, numbers, and users.
Generics carry the concrete type through the function. No `any`, no casting.
function identity<T>(x: T): T { return x; } const a = identity("hi"); // T = string const b = identity(42); // T = number const c = identity({ id: 1 }); // T = { id: number } function first<T>(arr: T[]): T | the missing detail { return arr[0]; } const n = first([1, 2, 3]); // number | the missing detailConstraints narrow the allowed types
`extends` says: T can be any type as long as it has an id string. Lets you use i.id safely.
function byId<T extends { id: string }>(items: T[], id: string): T | the missing detail { return items.find((i) => i.id === id); } type User = { id: string; name: string }; const users: User[] = [{ id: "u_1", name: "Ada" }]; const u = byId(users, "u_1"); // typed as User | the missing detail console.log(u?.name);Key terms in this lesson
The big idea: generics carry types through reusable functions. Add constraints when you need properties, lean on built-in utility types, and stop when it stops helping.
End-of-lesson quiz
Check what stuck
6 questions · Score saves to your progress.
Tutor
Curious about “TypeScript Generics”?
Ask anything about this lesson. I’ll answer using just what you’re reading — short, friendly, grounded.
Progress saved locally in this browser. Sign in to sync across devices.
Related lessons
Keep going
Creators · 50 min
Installing and Using Claude Code CLI
Claude Code is Anthropic's terminal-native coding agent. Let's install it, wire it to a project, and use the features most engineers miss on day one.
Creators · 45 min
Installing and Using the OpenAI Codex CLI
Codex CLI is OpenAI's terminal coding agent. It runs locally, supports MCP, and ships a codex cloud mode for background tasks. Let's install it and compare it honestly to Claude Code.
Creators · 40 min
Agents vs. Autocomplete — the Mental Model Shift
Autocomplete is a suggestion. An agent is an actor. The mental model you bring to each is different, and conflating them is the number-one reason teams trip over AI coding.
