Sub topic 2
Modeling a Task with TypeScript
What this chapter assumes
You should be comfortable with basic TypeScript (types, interfaces, classes) and with JavaScript arrays and objects. You also need the project from the previous chapter, created with ng new task-list. Nothing here needs the dev server. You will write a few small files and let the compiler check them.
Why model the data first
Every later part of the app handles a task: the service stores it, the list renders it, the item component receives it, the form creates it, and the HTTP layer sends and receives it. If each part guesses the shape of a task on its own, mistakes only show up at runtime. For example, a template might read task.name when the data has title.
A single TypeScript type moves those mistakes to compile time. The compiler checks the TypeScript code against it. Angular's template compiler also checks templates against it when strict template checking is on, which it is in new projects.
The Task interface
Create src/app/task.ts:
export interface Task {
id: number;
title: string;
done: boolean;
}An interface describes the shape of an object: which property names it has and what type each one holds. A value is a Task if it has a numeric id, a string title, and a boolean done. TypeScript checks this by shape, not by class or origin. Any object literal, JSON result, or spread copy with those properties qualifies. This is called structural typing.
Each field has a job:
ididentifies a task. The service uses it to toggle or remove one task, and@foruses it to track rows. It is anumberhere. Later, when a backend assigns ids, the type may need to change.titleis the text the user typed.doneis a boolean flag, not a string such as"yes". Choosing one representation now avoids conversion code later.
Other files import the interface with import { Task } from './task';. The Angular CLI puts each file in the same src/app folder, so a relative path like ./task is enough.
Strict mode does the checking
An interface only helps if the compiler enforces it. A project created by a recent Angular CLI turns on strict checking in tsconfig.json. Open the file and confirm these settings:
{
"compileOnSave": false,
"compilerOptions": {
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"angularCompilerOptions": {
"strictTemplates": true
}
}The real file has more options. These are the ones that matter here. strict enables strictNullChecks and noImplicitAny. With strictNullChecks, a Task | undefined cannot be used as a Task until you check for undefined. With strictTemplates, the same checks apply to expressions inside templates. If you turn these off, much of the interface's value goes away.
What the compiler catches
Try these in a scratch file such as src/app/scratch.ts, then delete it afterward:
import { Task } from './task';
const ok: Task = { id: 1, title: 'Write chapter', done: false };
// Error: Property 'done' is missing
const missing: Task = { id: 2, title: 'No flag' };
// Error: Type 'string' is not assignable to type 'number'
const wrongType: Task = { id: '3', title: 'Bad id', done: false };
// Error: Object literal may only specify known properties
const extra: Task = { id: 4, title: 'Extra', done: false, priority: 1 };
console.log(ok.title.toUpperCase());The third error is the excess property check. It applies only to object literals assigned directly to a typed target. If you first assign the object to a variable, then assign that variable to a Task, the extra property passes silently. Structural typing allows extra properties on non-literal values.
Interface or type alias
Both can describe an object shape, and for Task either works.
| Feature | `interface` | `type` alias | Column |
|---|---|---|---|
| Describes an object shape | Yes | Yes | |
| Extends another type | `extends` keyword | Intersection with `&` | |
| Can be reopened and merged by repeating the declaration | Yes | No | |
| Can name a union such as `'a' \ | 'b'` | No | Yes |
| Can name a primitive, tuple, or mapped type | No | Yes |
A common convention is to use interface for object shapes that other code implements or extends, and type for unions and computed types. This tutorial follows it: Task is an interface, and the derived types below are aliases. The Angular style guide does not mandate either, so follow your team's rule if it has one.
Deriving related types
The app needs more than one view of a task. The form produces a title but no id. An update might change only some fields. Writing a second interface by hand for each view means several definitions that can drift apart. Derive them from Task instead:
import { Task } from './task';
/** What a caller supplies when creating a task. */
export type NewTask = Omit<Task, 'id' | 'done'>;
/** A partial change to an existing task; the id cannot change. */
export type TaskPatch = Partial<Omit<Task, 'id'>>;
/** A task that code must not modify in place. */
export type FrozenTask = Readonly<Task>;
export function applyPatch(task: Task, patch: TaskPatch): Task {
return { ...task, ...patch };
}
const base: Task = { id: 1, title: 'Draft', done: false };
const updated = applyPatch(base, { done: true });
console.log(updated);
const frozen: FrozenTask = base;
// frozen.done = true; // Error: Cannot assign to 'done' because it is a read-only property
console.log(frozen.title);Here is what each utility type does:
Omit<Task, 'id' | 'done'>copiesTaskwithout the listed keys, which leaves{ title: string }.Partial<...>makes every property optional, so a patch can carry justtitle, justdone, or both.Readonly<Task>marks every property read-only. It is enforced at compile time only. The object is not frozen at runtime.
If you rename title to name in Task, all three types change with it. The compiler then flags every place that used the old name.
The final chapter code needs only Task for now. NewTask and TaskPatch are tools for later chapters, when ids come from a backend and updates become partial.
Immutable updates and the model
The next chapter holds tasks in a signal. A signal notices a change when you set it to a new value, so replacing the array and its objects fits well. The interface supports that style. The service you will write later contains this line:
list.map(t => (t.id === id ? { ...t, done: !t.done } : t))The spread { ...t, done: !t.done } builds a new object. TypeScript infers its type as Task, because it has all three properties with matching types. If you wrote { ...t, done: 'yes' }, the compiler would reject it when the result must be a Task. Using Readonly<Task> or ReadonlyArray<Task> for values you hand out makes accidental in-place edits (t.done = true, list.push(...)) compile errors rather than hidden bugs.
Unions and narrowing
A union type limits a value to a fixed set. A task filter is a good example:
import { Task } from './task';
export type TaskFilter = 'all' | 'active' | 'done';
export function filterTasks(tasks: readonly Task[], filter: TaskFilter): Task[] {
switch (filter) {
case 'all':
return [...tasks];
case 'active':
return tasks.filter(t => !t.done);
case 'done':
return tasks.filter(t => t.done);
}
}The function has no default branch and no return after the switch, and it still compiles under noImplicitReturns. TypeScript sees that every member of TaskFilter is handled, so the end of the function is unreachable. If you later add 'overdue' to the union, this function fails to compile until you handle it. The app in this tutorial does not need a filter, so treat this as an example of the technique.
Narrowing matters just as much for lookups. tasks.find(...) returns Task | undefined, and strict mode makes you handle the missing case:
import { Task } from './task';
export function titleOf(tasks: readonly Task[], id: number): string {
const found = tasks.find(t => t.id === id);
return found ? found.title : '(not found)';
}You will meet this again in the detail route, where an id from the URL may match no task.
The model disappears at runtime
Interfaces are erased during compilation. No Task check exists in the JavaScript that runs in the browser. This has two consequences:
- You cannot test a value with
value instanceof Taskortypeof value === 'Task'. - Data that arrives from outside, such as JSON from an HTTP response, is not validated. A call such as
http.get<Task[]>(url)only tells the compiler what to assume. If the server sends{ "id": "7" }, the program keeps running with a string where the type says number.
Treat the type as a promise you keep inside your own code. At the HTTP boundary, you decide how much to trust the backend, and the HTTP chapter returns to this.
One more point concerns exports. Re-exporting an interface from a barrel file needs export type { Task } from './task'; when isolatedModules is on. A plain export { Task } fails because the compiler cannot tell it is a type.
Common mistakes
| Mistake | Symptom | Fix | Column |
|---|---|---|---|
| Declaring `done` as `boolean \ | undefined` "to be safe" | Every use needs an `undefined` check | Keep it `boolean` and set it when creating the task |
| Defining `Task` twice (service and component) | Types drift apart without errors | One shared `task.ts`, imported everywhere | |
| Using `any` for tasks from a response | Typos in templates are not caught | Type the response with `Task[]` | |
| Mutating `task.done = true` on shared objects | Signals and `OnPush` views do not update | Create a new object with spread | |
| Expecting runtime checks from the interface | Bad server data passes silently | Validate at the HTTP boundary if you need safety |
How the types connect
The next diagram shows how one interface feeds the rest of the app.
Checking your work
Run ng build or ng serve. A type error in your scratch file appears in the terminal with the file and line. Delete the scratch file before moving on, because the error lines above are intentional and would break the build. The only file the next chapters rely on is src/app/task.ts.
Exercise
You write const t: Task = { id: 1, title: 'A', done: false, tag: 'home' }; and get an error, but const raw = { id: 1, title: 'A', done: false, tag: 'home' }; const t: Task = raw; compiles. Why do the two differ, and how would you define a type for a task that must also carry an optional tag?
Show answer
The first is an object literal assigned directly to a typed target, so TypeScript applies the excess property check and rejects the unknown tag. The second assigns an existing variable. Structural typing only requires that raw has at least the properties of Task, so the extra tag is allowed. To model a tag, add tag?: string; to Task (or define type TaggedTask = Task & { tag?: string }), so the property is a known, optional part of the type.
Exercise
Write a type TaskTitleUpdate derived from Task that requires only id and title, with no done field. Use utility types, not a new hand-written interface.
Show answer
type TaskTitleUpdate = Pick<Task, 'id' | 'title'>; Pick keeps only the listed keys, so the result is { id: number; title: string }. Omit<Task, 'done'> gives the same shape.