Explain it simply
Explain it simply
Part 2's TaskManager mixes two jobs. One is the task rules: incrementing ids and changing statuses. The other is storing things in an array and searching them, and that second job has nothing to do with tasks. You need exactly the same storage for tags, users or projects.
Think of a cupboard. It can "store", "show everything" and "find" without knowing what is inside. A generic Repository<T> is that cupboard, and writing new Repository<Task>() is the moment you stick a label on it saying "only tasks go in here".
Problem → Why → Solution
The problem: one copied class per type
Say you now want to group tasks with tags. The fastest move is to copy the storage class and replace Task with string. It works, but the day you fix a bug in find() you must fix it in two places, and a User store makes it three.
The other tempting "fix" is a single class with items: any[]. Now numbers can slip into the task store, and nobody checks the .title you read from whatever find() returns.
class TaskStore {
private items: Task[] = [];
add(item: Task): void { this.items.push(item); }
find(match: (t: Task) => boolean): Task | undefined {
return this.items.find(match);
}
}
// The same code again; only the type changed.
class TagStore {
private items: string[] = [];
add(item: string): void { this.items.push(item); }
find(match: (t: string) => boolean): string | undefined {
return this.items.find(match);
}
}Why do we need a generic?
The two classes have identical logic and differ only in the type. Just as a function takes a value as a parameter, a generic takes a type as a parameter (T). You write the logic once and keep full type safety.
Core concept: generic storage plus task rules
In class Repository<T>, T is a placeholder type. Writing new Repository<Task>() turns every T inside the class into Task: add() accepts only Task and find() returns Task | undefined. new Repository<string>() makes the very same code work for strings. At runtime there is just one class and no T at all; every check happens at compile time.
What if you write new Repository() with no type argument? There is no constructor argument to infer T from, so TypeScript picks unknown (not any). add() then accepts anything, and reading .title from something returned by getAll() fails with "Object is of type 'unknown'". So wherever there is nothing to infer from, such as a field initializer, always write <Task>.
TaskManager does not extend Repository<Task>; it holds one in a private field. This is composition, a "has-a" relationship. With extends, add() would become a public method of TaskManager and callers could insert tasks directly, skipping the id counter and the status rules. With composition, Repository only stores, and TaskManager alone owns the task rules.
There are two polish steps as well. getAll() returns readonly T[], so callers can read the list but push() is a compile error. getStats() returns a labeled tuple, [total: number, done: number]: the length and order are fixed, and the labels show in the editor which slot is which. Finally, updateStatus() no longer returns false; it throws a TaskNotFoundError, so even a caller who forgets to check cannot silently lose the failure.
| Return false (Part 2) | Throw an error (Part 3) | |
|---|---|---|
| If the caller forgets | The failure is silently lost | The program notices at once |
| Can it explain why | Only true or false | A message and an error type |
| Good fit for | Misses that are routine | Situations that should not happen |
- Repository<T> only stores and finds
- <Task> labels the cupboard
- TaskManager owns it and keeps rules
- Stats as a tuple, misses as errors
The generic class answers "how do we store things?"; TaskManager answers "how must a task behave?".
General pattern
class Store<T> {
private items: T[] = [];
add(item: T): void { /* push */ }
all(): readonly T[] { return this.items; }
}
class Service {
private store = new Store<Entity>(); // composition, explicit <T>
stats(): [count: number, active: number] { /* ... */ }
}A generic class handles storage; a service class keeps one in a private field and exposes its own rules and result types such as a tuple.
Part 3 code: the finished project
TaskStatus and Task have not changed since Part 1. Part 2's private tasks array is replaced by private repo = new Repository<Task>(), and updateStatus() now throws. At the end the demo reuses Repository for strings. The error line uses console.log only so all output appears in one stream; a real CLI would write it with console.error (stderr).
enum TaskStatus {
Todo = "TODO",
InProgress = "IN_PROGRESS",
Done = "DONE",
}
interface Task {
id: number;
title: string;
status: TaskStatus;
priority: "low" | "medium" | "high";
}
class Repository<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getAll(): readonly T[] {
return this.items;
}
find(predicate: (item: T) => boolean): T | undefined {
return this.items.find(predicate);
}
}
class TaskNotFoundError extends Error {
constructor(id: number) {
super(`Task #${id} not found`);
this.name = "TaskNotFoundError";
}
}
class TaskManager {
private repo = new Repository<Task>();
private nextId = 1;
addTask(title: string, priority: Task["priority"]): Task {
const task: Task = { id: this.nextId++, title, status: TaskStatus.Todo, priority };
this.repo.add(task);
return task;
}
updateStatus(id: number, status: TaskStatus): void {
const task = this.repo.find((t) => t.id === id);
if (!task) throw new TaskNotFoundError(id);
task.status = status;
}
getStats(): [total: number, done: number] {
const all = this.repo.getAll();
const done = all.filter((t) => t.status === TaskStatus.Done).length;
return [all.length, done];
}
}
const manager = new TaskManager();
manager.addTask("Learn generics", "high");
manager.addTask("Write tests", "medium");
manager.updateStatus(1, TaskStatus.Done);
const [total, done] = manager.getStats();
console.log(`Total: ${total}, Done: ${done}`);
try {
manager.updateStatus(99, TaskStatus.Done);
} catch (err) {
if (err instanceof TaskNotFoundError) console.log(`Error: ${err.message}`);
else throw err;
}
const tags = new Repository<string>();
tags.add("work");
tags.add("urgent");
console.log(`Tags: ${tags.getAll().join(", ")}`);Code breakdown
- Read-only view
getAll(): readonly T[] {Callers can read and filter the list, but push() or splice() is a compile error, so nobody outside can rewrite the repository's array.
- A named error type
class TaskNotFoundError extends Error {A dedicated error class lets catch tell "task not found" apart from any other bug using instanceof.
- Composition with explicit <T>
private repo = new Repository<Task>();TaskManager has a Repository rather than being one. Without <Task>, T would become unknown.
- Throw instead of false
if (!task) throw new TaskNotFoundError(id);The narrowing is the same as before, but a miss is now reported as an error instead of a return value. Below this line task is a Task.
- Labeled tuple
getStats(): [total: number, done: number] {Exactly two elements in a fixed order. const [total, done] = ... destructures by position, not by label name.
- Narrow the caught value
if (err instanceof TaskNotFoundError) console.log(`Error: ${err.message}`);Under strict mode err is unknown. instanceof narrows it before .message is read, and any unexpected error is rethrown.
Total: 2, Done: 1
Error: Task #99 not found
Tags: work, urgentLooking back at the whole project
| Part | TypeScript features added |
|---|---|
| 1. Setup | String enum, literal union, interface, indexed access type |
| 2. Class | Private fields, narrowing find(), boolean results, filter() |
| 3. Polish | Generic class, composition, readonly array, labeled tuple, custom error |
To keep going, save the tasks to a JSON file and load them when the program starts again. Data read from a file is unknown, so validate it with a zod schema, as in the async APIs lesson, before it enters the repository. When the code grows, split the Task types, Repository and TaskManager into three ESM modules.
In real projects
In real projects
The repository pattern is everywhere in backend code. Some ORM libraries hand you a generic Repository<Entity> per entity. Teams often write a Repository<T> interface with two implementations: an in-memory array like this lesson's for tests, and a database-backed one for production. Because the service class depends only on the interface, tests run fast without a database.
Custom error classes are usually mapped to HTTP status codes at the API layer: TaskNotFoundError becomes 404 and a ValidationError becomes 400. And you already use tuple-returning APIs every day: React's useState() returns a [value, setValue] tuple, which is why you can destructure it with any names you like. When a team later needs a method such as getById(), they add a constraint like T extends { id: number }, which is exactly this lesson's challenge.
Common mistakes
Common mistakes
Leaving out the type argument
private repo = new Repository(); makes T unknown (people often assume any, but it is unknown). add() then accepts numbers too, and every use of a find() result turns into an error. Write new Repository<Task>().
Swapping the tuple order
A slip like return [done, all.length]; still compiles because both elements are numbers, and prints "Total: 1, Done: 2". Labels are documentation; they do not check the order. Once there are more than two or three values, returning an object such as { total, done } is safer.
Reading err.message straight away in catch
With strict mode, err in catch (err) is unknown, so err.message is a compile error. Do not paper over it with (err as Error): anything can be thrown. Narrow with instanceof and rethrow what you do not recognise.
Best practices
Best practices
- Extract a generic once two classes really duplicate logic, not in case it might be useful someday
- Add an extends constraint only when the code needs a property of T
- When returning an internal collection, return readonly T[] or a copy
Mini challenge
An IdRepository for anything with an id
Repository<T> knows nothing about T, so it cannot offer getById(). Write an IdRepository<T> whose T is constrained to have { id: number }, and try it with a Note type.
- Use a constraint: class IdRepository<T extends { id: number }>
- getById(id) returns T | undefined
- remove(id) returns true only if something was removed
- Add two Note { id; text } items and remove the same one twice
// TODO: constrain T so every item is guaranteed to have id: number
class IdRepository<T> {
private items: T[] = [];
add(item: T): void {
// TODO
}
getById(id: number): T | undefined {
// TODO: item.id only compiles once T is constrained
}
remove(id: number): boolean {
// TODO: filter it out, assign back, report whether the length changed
}
}
interface Note {
id: number;
text: string;
}
// TODO: create an IdRepository<Note>, add two notes, look one up, remove one twiceExpected: It prints "Call the bank", then true false from the two removes, then "Notes left: 1". new IdRepository<string>() should be a compile error.
Show hint
Without a constraint, item.id fails with "Property 'id' does not exist on type 'T'". Writing <T extends { id: number }> guarantees an id, whatever T turns out to be.
Show solution
class IdRepository<T extends { id: number }> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getById(id: number): T | undefined {
return this.items.find((item) => item.id === id);
}
remove(id: number): boolean {
const before = this.items.length;
this.items = this.items.filter((item) => item.id !== id);
return this.items.length < before;
}
count(): number {
return this.items.length;
}
}
interface Note {
id: number;
text: string;
}
const notes = new IdRepository<Note>();
notes.add({ id: 1, text: "Buy milk" });
notes.add({ id: 2, text: "Call the bank" });
console.log(notes.getById(2)?.text);
console.log(notes.remove(1), notes.remove(1));
console.log(`Notes left: ${notes.count()}`);
// new IdRepository<string>(); // error: 'string' does not satisfy '{ id: number; }'Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Merge classes that share logic and differ only in type into one generic class
- Write the type argument (<Task>) wherever nothing can be inferred, or T becomes unknown
- Composition reuses the storage while keeping the task rules protected
- Tuple labels do not check order, and a caught err must be narrowed with instanceof
TypeScript Handbook — TypeScript