Explain it simply
Explain it simply
In Part 1 the task list is like a notebook lying open in the middle of the file: anyone can tear out a page or rewrite the numbers. In Part 2 the notebook goes behind a counter and a clerk, TaskManager, looks after it. You can ask "add a task", "move #1 to In progress" or "show me what is done", but you can no longer grab the notebook yourself.
A class keeps the data (the tasks array and nextId) and the methods that work on that data in one place. The private keyword turns any attempt to touch that data from outside into a compile error.
Problem → Why → Solution
The problem: global state anyone can change
The Part 1 code is fine for a tiny program. But as the file grows, any function in it can change tasks and nextId. If someone adds a "reset" helper that sets only nextId back to 1, two tasks end up as #1 and updateStatus(1, ...) changes the wrong one.
The second problem is that only one list can exist. If you want separate "Work" and "Home" lists, you have to copy every variable and every function.
const tasks: Task[] = [];
let nextId = 1;
// ...200 lines later, a helper someone added:
function resetCounter(): void {
nextId = 1; // ids now repeat: the next task is #1 again
}
// A second "Home" list? Copy tasks, nextId and every function.Why is this risky?
The more places that can change the data, the harder it is to find out who changed a value. When the state is locked inside a class and only its methods may change it, the rules (ids never repeat, status is always an enum value) are guarded in exactly one place.
Core concept: bundle state and behaviour in a class
A class is a blueprint. Every new TaskManager() creates a fresh object that owns its own tasks array and nextId, so if you create a work manager and a home manager, the ids of one never affect the other. Inside the methods, this.tasks means "the tasks of this particular object".
private is a rule for the TypeScript compiler. Writing manager.tasks outside the class is a compile error: "Property 'tasks' is private". But like all types, the word private disappears at runtime. The JavaScript object still has a tasks property, which console.log(manager) or JSON.stringify(manager) will show. If you need real runtime privacy, use JavaScript's #tasks hash-private field.
The two new methods reuse ideas from earlier lessons. In updateStatus(), find() returns Task | undefined, so if (!task) return false; narrows it before task.status is changed. When nothing matches, the method returns false and lets the caller decide what to do. filterByStatus() returns the new array that filter() builds. The array is new, but the task objects inside it are the very same objects the manager holds.
Notice how each method's return type tells the caller what to expect. addTask() returns Task because the caller usually needs the new id. updateStatus() returns boolean because the only question is "did it work?". filterByStatus() returns Task[], which may be empty but is never undefined, so callers can always call forEach() on it. listTasks() returns void because it only prints. Choosing these types on purpose is part of designing a class, not an afterthought; in Part 3 we replace the boolean with a thrown error and look at the trade-off.
filter() copies the array, not the objects
------------------------------------------
manager.tasks ------> [ ref1 , ref2 ]
| |
v v
{ id: 1 } { id: 2 }
^
|
filterByStatus() ---> [ ref1 ] (new array, same object)| Part 1 (functions) | Part 2 (class) | |
|---|---|---|
| Where state lives | Global variables | Private fields |
| How many lists | Exactly one | One per new instance |
| Who can change it | Any code in the file | Only the class methods |
- new builds an object with own state
- Only methods touch private fields
- Narrow find() before using it
- filter() hands back a new array
Callers only ask through methods, so later you can swap the array for a Map or a database without touching their code.
General pattern
class Manager {
private items: Item[] = [];
add(item: Item): Item { this.items.push(item); return item; }
update(id: number, change: Partial<Item>): boolean {
const found = this.items.find((i) => i.id === id);
if (!found) return false; // narrowed: Item | undefined -> Item
Object.assign(found, change);
return true;
}
}Keep state in private fields, change it only through methods, and check find() for undefined before using the result.
Part 2 code: the TaskManager class
TaskStatus and Task are unchanged from Part 1. What changes: addTask() and listTasks() become methods, addTask() now returns the Task it created, and there are two new methods, updateStatus() and filterByStatus(). The demo also tries a missing id, #99, so you can see the false result.
enum TaskStatus {
Todo = "TODO",
InProgress = "IN_PROGRESS",
Done = "DONE",
}
interface Task {
id: number;
title: string;
status: TaskStatus;
priority: "low" | "medium" | "high";
}
class TaskManager {
private tasks: Task[] = [];
private nextId = 1;
addTask(title: string, priority: Task["priority"]): Task {
const task: Task = {
id: this.nextId++,
title,
status: TaskStatus.Todo,
priority,
};
this.tasks.push(task);
return task;
}
listTasks(): void {
this.tasks.forEach((t) =>
console.log(`#${t.id} [${t.status}] ${t.title} (${t.priority})`)
);
}
updateStatus(id: number, status: TaskStatus): boolean {
const task = this.tasks.find((t) => t.id === id);
if (!task) return false;
task.status = status;
return true;
}
filterByStatus(status: TaskStatus): Task[] {
return this.tasks.filter((t) => t.status === status);
}
}
const manager = new TaskManager();
manager.addTask("Learn generics", "high");
manager.addTask("Deploy project", "medium");
console.log("update #1:", manager.updateStatus(1, TaskStatus.InProgress));
console.log("update #99:", manager.updateStatus(99, TaskStatus.Done));
console.log("In Progress tasks:");
manager.filterByStatus(TaskStatus.InProgress).forEach((t) =>
console.log(`- ${t.title}`)
);
manager.listTasks();Code breakdown
- Private state
private tasks: Task[] = [];Each instance gets its own array, and writing manager.tasks outside the class is a compile error.
- Return the new task
return task;Returning the Task lets the caller learn its id immediately and use it in a later updateStatus() call.
- find() may miss
const task = this.tasks.find((t) => t.id === id);find() returns Task | undefined; the type itself warns you that the search can come back empty.
- Narrow, then mutate
if (!task) return false;Below this line task is narrowed to Task. task.status = status changes the real object inside the array, which is why listTasks() shows [IN_PROGRESS].
- A new array
return this.tasks.filter((t) => t.status === status);filter() leaves the original array alone and returns a new array of the matching objects.
update #1: true
update #99: false
In Progress tasks:
- Learn generics
#1 [IN_PROGRESS] Learn generics (high)
#2 [TODO] Deploy project (medium)- Search this.tasks by id
- Result is Task | undefined
- undefined: return false
- Task: change status, return true
id #1 (exists)
true
id #99 (missing)
false
find() hands you the real object
updateStatus() works because find() returns a reference to the object in the array, not a copy. That is useful, but it can also leak out of the class. If a caller takes a task from filterByStatus() and writes t.status = TaskStatus.Done, the manager's data changes too, bypassing whatever rules updateStatus() enforces.
For this project we accept that. In Part 3 the method that returns the whole list will return readonly Task[], so callers cannot push() into it. To protect the fields as well, you can return Readonly<Task> or a copy ({ ...task }).
In real projects
In real projects
In backend frameworks this pattern is usually called a service class. Classes such as OrderService or CartService keep their data private and only allow changes through methods like addItem() or updateStatus(). Frontend stores work the same way.
In an API, a route handler often turns a false from updateStatus() into an HTTP 404 Not Found. Because callers depend only on the methods, you can change the storage from an array to a Map<number, Task>, and later to a database table, without touching the rest of the code as long as the method signatures stay the same. Unit tests get easier too: each test starts with its own new TaskManager(), so tests never share state.
Common mistakes
Common mistakes
Throwing away the result of filter()
Writing removeTask() as just this.tasks.filter((t) => t.id !== id); removes nothing, because filter() returns a new array and leaves the original alone. Assign it back: this.tasks = this.tasks.filter(...). The compiler will not warn you, because calling filter() and ignoring its result is perfectly legal TypeScript.
Expecting private to hide data at runtime
private is only a compile-time check. JSON.stringify(manager) still prints {"tasks":[...],"nextId":3}. If something such as a token must stay hidden at runtime, use a #private field.
Detaching a method and losing this
const add = manager.addTask; add("x", "low"); runs with this set to undefined and throws a TypeError when it reads this.nextId. To pass a method as a callback, wrap it: (title) => manager.addTask(title, "low").
Best practices
Best practices
- Make fields private by default and open a method only when outside code really needs it
- Name methods after intent (updateStatus, filterByStatus) instead of exposing a generic setTasks setter
- For methods that can miss, pick one signal (undefined, false or an error) and use it consistently across the class
Mini challenge
Add removeTask() and countByPriority()
Add two methods to the TaskManager class. removeTask() deletes a task by id and reports whether anything was removed. countByPriority() returns how many tasks exist for each priority.
- Write removeTask(id: number): boolean with filter() and store the result back in this.tasks
- Return false for an id that does not exist
- countByPriority() returns Record<Task["priority"], number>
- Priorities with no tasks still appear with 0
// Add these methods inside the TaskManager class from the lesson.
removeTask(id: number): boolean {
// TODO: remember how many tasks there were
// TODO: keep every task except this id, and assign the result back
// TODO: return true only if the length went down
}
countByPriority(): Record<Task["priority"], number> {
// TODO: start from { low: 0, medium: 0, high: 0 }
// TODO: loop over this.tasks and add 1 to counts[t.priority]
}Expected: removeTask(2) prints true the first time and false the second, then { low: 1, medium: 0, high: 1 } is printed.
Show hint
An object typed Record<Task["priority"], number> must have all three keys, so start with three zeros. counts[t.priority]++ is type-safe because t.priority is one of those keys.
Show solution
enum TaskStatus {
Todo = "TODO",
InProgress = "IN_PROGRESS",
Done = "DONE",
}
interface Task {
id: number;
title: string;
status: TaskStatus;
priority: "low" | "medium" | "high";
}
class TaskManager {
private tasks: Task[] = [];
private nextId = 1;
addTask(title: string, priority: Task["priority"]): Task {
const task: Task = { id: this.nextId++, title, status: TaskStatus.Todo, priority };
this.tasks.push(task);
return task;
}
removeTask(id: number): boolean {
const before = this.tasks.length;
this.tasks = this.tasks.filter((t) => t.id !== id);
return this.tasks.length < before;
}
countByPriority(): Record<Task["priority"], number> {
const counts: Record<Task["priority"], number> = { low: 0, medium: 0, high: 0 };
for (const t of this.tasks) counts[t.priority]++;
return counts;
}
}
const home = new TaskManager();
home.addTask("Pay electricity bill", "high");
home.addTask("Fix the shelf", "high");
home.addTask("Water the plants", "low");
console.log(home.removeTask(2));
console.log(home.removeTask(2));
console.log(home.countByPriority());Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class bundles state with methods, and every new instance gets its own state
- private is a compile-time rule; use #private when you need runtime privacy
- Narrow find()'s Task | undefined before using it, and return false when nothing matches
- filter() returns a new array, but the objects inside it are the originals
TypeScript Handbook — TypeScript