Explain it simply
Explain it simply
Starting with this lesson, you will build a small Task Manager that runs in the terminal over three lessons. Part 1 writes almost no features. First we decide the data shape: what exactly is a task made of?
Think of a paper form. It has a box for the title and three checkboxes for status: Todo, In progress, Done. Because there are checkboxes, nobody can write 'sort of finished' in the status field. In TypeScript the interface is the form, and enums and union types are the checkboxes. Once the form is drawn, the compiler checks every line you add in Part 2 and Part 3 against this shape.
Problem → Why → Solution
The problem: a task list with no shape
Here is a quick first draft written without types. The array is declared as any[], so it accepts every object. On the second task, status was typed as "Done" with a capital D, and the field name priority was misspelled as "priorty".
No error appears anywhere. When the code looks for finished tasks it compares against "done" in lowercase and gets 0. The user did finish a task, but the app reports that nothing is done. Bugs like this are often noticed weeks later, when someone finally asks why the counter never moves.
const tasks: any[] = [];
tasks.push({ id: 1, title: "Write README", status: "todo", priority: "high" });
tasks.push({ id: 2, title: "Fix login bug", status: "Done", priorty: "hgh" });
const done = tasks.filter((t) => t.status === "done");
console.log(done.length); // 0 - nobody noticed "Done" or "priorty"Why didn't the compiler stop this?
any tells the compiler "do not check this value". If the shape of a task is never written down, TypeScript has nothing to compare against. Only an interface plus closed value sets let it catch these typos at compile time, before the program runs.
Core concept: design the data first
When you start a new project, do not jump straight into functions. First write down, as types, what data the app handles. Those types are the contract for the whole project: every new function and every later feature has to respect them. For this Task Manager we make four decisions in order.
1. List the fields and their types
A task has an id (number), a title (string), a status and a priority. Once these live in interface Task, the compiler rejects an object literal that is missing a field or has a misspelled one.
2. Close the open-ended values
Status and priority cannot be any string; there are only a few valid choices. Status becomes a string enum. An enum exists at runtime as a real TaskStatus object, so later you can loop over Object.values(TaskStatus) to build a menu, and because each member has a string value such as "TODO", logs show readable text instead of 0, 1, 2. Priority becomes a literal union: lighter, with no runtime object, and you write plain strings like "high".
3. Reuse a type instead of retyping it
addTask() does not repeat "low" | "medium" | "high" in its parameter; it writes Task["priority"], an indexed access type. If you later add "urgent" to the interface, the function picks it up automatically, because there is one source of truth.
4. Keep the state in a typed array
const tasks: Task[] = [] means the variable can never be reassigned, yet push() still adds items to the array. nextId changes every time a task is added, so it must be let.
| String enum (status) | Literal union (priority) | |
|---|---|---|
| At runtime | Emits a real object | Nothing remains (erased) |
| How you write a value | TaskStatus.Done | "high" |
| Good fit for | Sets you iterate or name | Simple closed choices |
- List the fields a task needs
- Close value sets with enum or union
- Store tasks in a typed array
- Write functions over that array
When the shape changes, edit the interface in one place and let the compiler point at every line that no longer fits.
General pattern
enum Status { First = "FIRST", Second = "SECOND" }
type Level = "low" | "high";
interface Item {
id: number;
status: Status;
level: Level;
}
const items: Item[] = [];
function addItem(level: Item["level"]): void { /* build + push */ }Define closed sets with an enum or a union, combine them in an interface, then let the typed array and the functions refer back to that interface.
Part 1 code: add tasks and list them
This file holds only the data shape and two functions. addTask() assigns the next id automatically and starts every task as Todo; listTasks() prints one task per line. Part 2 reorganises exactly this code into a class, so keep the names in mind.
enum TaskStatus {
Todo = "TODO",
InProgress = "IN_PROGRESS",
Done = "DONE",
}
interface Task {
id: number;
title: string;
status: TaskStatus;
priority: "low" | "medium" | "high";
}
const tasks: Task[] = [];
let nextId = 1;
function addTask(title: string, priority: Task["priority"]): void {
const task: Task = {
id: nextId++,
title,
status: TaskStatus.Todo,
priority,
};
tasks.push(task);
}
function listTasks(): void {
tasks.forEach((t) => {
console.log(`#${t.id} [${t.status}] ${t.title} (${t.priority})`);
});
}
addTask("Learn TypeScript generics", "high");
addTask("Write project README", "low");
listTasks();Code breakdown
- String enum member
Todo = "TODO",Each member has a string value, which is why the output shows [TODO]. Without explicit values the members would be numbers starting at 0.
- Literal union field
priority: "low" | "medium" | "high";Priority must be one of exactly three strings, so a typo such as "hgh" becomes a compile error.
- Indexed access type
function addTask(title: string, priority: Task["priority"]): void {The parameter borrows the union from the Task interface instead of repeating it, so editing the interface updates this signature too.
- Auto-incrementing id
id: nextId++,nextId++ uses the current value (1) first and then increments it, so the first task gets #1 and the second gets #2.
- One line per task
tasks.forEach((t) => {TypeScript already knows t is a Task, so t.status and t.title autocomplete and any field that does not exist is an error.
#1 [TODO] Learn TypeScript generics (high)
#2 [TODO] Write project README (low)Where this project goes next
This Part 1 code has one weakness. tasks and nextId are global variables, so any code in the file can write tasks.length = 0 and wipe the list, or set nextId = 1 and create duplicate ids. You also cannot keep two separate lists, say "Work" and "Home".
In Part 2 the state and functions move into a TaskManager class with private fields, and we add status updates and filtering. In Part 3 the storage logic is pulled out into a generic Repository<T>, and we add a stats tuple and error handling. The Task interface and the TaskStatus enum stay the same all the way to the end.
Enums produce runtime code
An enum is one of the few TypeScript features that emits a JavaScript object, not just a type. Projects that only strip types (for example Node.js type stripping, or the erasableSyntaxOnly compiler option) do not allow enums; there you would use an as const object plus a union type instead.
In real projects
In real projects
Issue trackers, order systems and support-ticket apps all have a status field with a closed set of values. Teams usually keep that enum or union in one shared types file so the database column, the API response and the frontend dropdown all use the same values. String values are readable in JSON, in logs and in the database, which makes debugging far easier.
One rule matters once data is stored: do not change the string value ("IN_PROGRESS") anymore, because existing rows still hold the old value. Renaming the member key (InProgress) in code is safe. When you add a new field such as dueDate, adding it as optional (?) first keeps older records valid.
Common mistakes
Common mistakes
Leaving enum members without values
Writing enum TaskStatus { Todo, InProgress, Done } makes the members 0, 1 and 2, so the log shows "#1 [0] ...". Worse, inserting a Blocked member in the middle later changes Done's number and silently changes the meaning of saved data. Give every member a string value.
Typing priority as plain string
With priority: string, addTask("Fix bug", "hgih") compiles, and the task silently disappears from any filter for "high". If you know the set of values, use a literal union.
Copy-pasting the union everywhere
If every signature repeats "low" | "medium" | "high", adding a value later always misses one spot. Refer to Task["priority"] or a type Priority alias instead.
Mini challenge
Add due dates and a status count
Extend the Part 1 code. Give Task an optional dueDate, let addTask() take the due date as an optional parameter, and write formatTask() and countByStatus().
- Add dueDate?: string to the Task interface
- addTask() returns the Task it created
- formatTask() appends "- due ..." when there is a due date and "- no due date" otherwise
- countByStatus(status) returns how many tasks have that status
// Reuse TaskStatus and Task from the lesson.
// TODO: add an optional dueDate (string) to the Task interface.
function addTask(
title: string,
priority: Task["priority"],
dueDate?: string,
): Task {
// TODO: create the task with the next id and status Todo, push it, return it
}
function formatTask(task: Task): string {
// TODO: "#1 [TODO] Title (high) - due 2026-12-01"
// or "#2 [TODO] Title (low) - no due date"
}
function countByStatus(status: TaskStatus): number {
// TODO: count the tasks whose status matches
}Expected: One line per task showing its due date or "no due date", followed by the counts Todo: 1 and Done: 1.
Show hint
Reading an optional field gives string | undefined, so check it with task.dueDate ? ... : .... For the count, filter(...).length works.
Show solution
enum TaskStatus {
Todo = "TODO",
InProgress = "IN_PROGRESS",
Done = "DONE",
}
interface Task {
id: number;
title: string;
status: TaskStatus;
priority: "low" | "medium" | "high";
dueDate?: string;
}
const tasks: Task[] = [];
let nextId = 1;
function addTask(
title: string,
priority: Task["priority"],
dueDate?: string,
): Task {
const task: Task = { id: nextId++, title, status: TaskStatus.Todo, priority, dueDate };
tasks.push(task);
return task;
}
function formatTask(task: Task): string {
const due = task.dueDate ? `due ${task.dueDate}` : "no due date";
return `#${task.id} [${task.status}] ${task.title} (${task.priority}) - ${due}`;
}
function countByStatus(status: TaskStatus): number {
return tasks.filter((t) => t.status === status).length;
}
addTask("Prepare demo", "high", "2026-12-01");
const readme = addTask("Update README", "low");
readme.status = TaskStatus.Done;
tasks.forEach((t) => console.log(formatTask(t)));
console.log(`Todo: ${countByStatus(TaskStatus.Todo)}`);
console.log(`Done: ${countByStatus(TaskStatus.Done)}`);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Start a project from its data shape (an interface), not from functions
- Use a string enum for sets you iterate, like status, and a literal union for simple choices like priority
- Keep each union in one place and reuse it with an indexed access type like Task["priority"]
- Global state is the weakness Part 2 fixes by moving everything into a class
TypeScript Handbook — TypeScript