Loading lesson…
Generics let a function work for many types while keeping type safety. The syntax looks scary and the concept is simple.
A generic is a placeholder that TypeScript fills in based on how you call the function. One `identity` works for strings, numbers, and users.
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 detailGenerics carry the concrete type through the function. No `any`, no casting.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);`extends` says: T can be any type as long as it has an id string. Lets you use i.id safely.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.
6 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-progx-ts-generics-creators
What is the main idea of "TypeScript Generics"?
Which concept is most central to "TypeScript Generics"?
What should a careful learner remember about "Built-in utility types"?
You want to use AI after this lesson. What is the safest next step?
How should AI output about generic be treated?
Name one way to verify an AI answer about generic.