Lesson 193 of 2116
TypeScript Generics
Generics let a function work for many types while keeping type safety. The syntax looks scary and the concept is simple.
Lesson map
What this lesson covers
Learning path
The main moves in order
- 1A Function, for Any Type
- 2generic
- 3constraint
- 4inference
Concept cluster
Terms to connect while reading
Section 1
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 | undefined {
return arr[0];
}
const n = first([1, 2, 3]); // number | undefinedConstraints 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 | undefined {
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 | undefined
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
15 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
The Landscape: Copilot vs. Cursor vs. Windsurf vs. Claude Code
The AI coding tool market fragmented fast. Let's map the 2026 landscape honestly: who is for autocomplete, who is for agents, who wins on cost, and what the tradeoffs actually feel like.
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.
