Sub topic 2
Modeling a Task with TypeScript
This chapter defines the Task type that every later piece of the app uses. It assumes you know basic TypeScript (types, interfaces, modules) and have created the Angular project from the previous chapter. You will write one small file, then see how the compiler uses it in the service, components, and templates.
Why model the data first
A task list moves the same object through many places: a service stores it, a list renders it, a form creates it, and an HTTP call sends it. If each place guesses the object's shape, a typo like task.titel fails only at runtime, or silently shows nothing.
A TypeScript type describes the shape once. The compiler then checks every place that uses it. Angular's templates are also type-checked in the default CLI setup, so a mistake in a template is reported when you build.
Defining the Task interface
Create src/app/task.ts:
export interface Task {
id: number;
title: string;
done: boolean;
}Each field has a job:
| Field | Type | Purpose |
|---|---|---|
| `id` | `number` | Identifies a task so it can be toggled, removed, and tracked in `@for`. |
| `title` | `string` | The text the user typed. |
| `done` | `boolean` | Whether the task is complete. |
An interface exists only at compile time. It produces no JavaScript, so it adds nothing to your bundle. The export keyword lets other files import it with import { Task } from './task';.
Using the type
Anything that holds or accepts a task can name the type. For example, the service in a later chapter stores Task[], and a child component declares input.required<Task>(). Here is a small function to see the checking in action:
import { Task } from './task';
export function describe(task: Task): string {
return `${task.title} (${task.done ? 'done' : 'open'})`;
}
const sample: Task = { id: 1, title: 'Write tests', done: false };
console.log(describe(sample));Now try breaking it. Each of these lines is a compile error:
const a: Task = { id: 1, title: 'x' };is missingdone.const b: Task = { id: '1', title: 'x', done: false };givesida string.describe(sample).foo;reads a property that astringdoes not have.
The compiler reports these in your editor and in ng serve, before you open the browser.
Design choices worth knowing
Interface or class. An interface describes plain objects. A class would add behavior and a constructor, but Angular signals and JSON from a server both work with plain objects, so an interface is simpler. It also fits the immutable updates used later, such as { ...t, done: !t.done }.
Who assigns the id. In this app the service assigns ids. The form only supplies a title. When you later load tasks over HTTP, the server will normally assign the id instead.
Optional or readonly fields. You could mark fields readonly to stop accidental mutation, such as readonly id: number;. This tutorial keeps the interface plain and relies on replacing objects rather than editing them. If you want the compiler to enforce that, adding readonly is a safe change.
Types are not runtime checks. TypeScript trusts you at boundaries. If a server returns { "id": "7" } and you call http.get<Task[]>(...), the compiler accepts it, but id is a string at runtime. The type describes what you expect, not what arrives.
Common errors
- Importing without
export. IfTaskis not exported, other files report "declares locally, but it is not exported". - Using
any. Typing a value asanyturns checking off for it. PreferTaskorunknown. - Making fields optional to silence errors. Writing
done?: booleanremoves the error but forces every user to handleundefined. Fix the object instead.
Exercise
You add createdAt: Date to the Task interface. What happens to existing code that builds a task like { id: 1, title: 'x', done: false }, and why?
Show answer
The compiler reports an error on each such object because the required createdAt property is missing. The interface is checked at every place a Task is created, so you must either supply the field, or declare it optional with createdAt?: Date if some tasks will not have it.
Exercise
A server returns { "id": "7", "title": "Pay rent", "done": false } and your code reads it with http.get<Task>(url). Does TypeScript report an error, and what is the type of id at runtime?
Show answer
No error is reported. The generic argument only tells the compiler what to assume. At runtime id is the string "7", not a number, because interfaces are erased and perform no validation.