Classes: properties, constructors, and methods
Write your first class: properties, a constructor that fills each new object through this, and methods that work on the object before the dot. Then move TaskKit’s list into a TaskStore class.
Write your first class: properties, a constructor that fills each new object through this, and methods that work on the object before the dot. Then move TaskKit’s list into a TaskStore class.
Tested with TypeScript 7.x · Node.js LTS
Open TaskKit's index.ts and trace where the list of tasks goes.
loadTasks in store.ts makes it: a Map. The add case changes it
by hand, and checks it against limit, a number kept in a box of its
own. Then the Map goes to saveTasks and printList, and its size
and the limit go to printSummary. Everything happens to the list, and
the list does nothing itself. Its rules (no empty task, no task twice,
five at most) sit inside the switch of index.ts, so no test can
check them, and any other place that adds a task would have to copy
them.
A house is not built that way. It comes with its rooms and its doors,
and nobody adds them by hand afterwards: an architect draws them once,
on a blueprint, and a builder puts up a whole street from it. Every
house has the same rooms, with its own furniture and its own family
inside. In TypeScript the blueprint is a class, and the houses are
objects built from it. By the end of this lesson you will write classes
of your own, and TaskKit's list will be one object, store, that
loads, adds and saves its own tasks.
In lesson 6.10 you made a Map with new Map<string, number>(), and
tally.set("milk", 1) changed that one Map: the method works on
the data of the value before the dot. new Error("…") (lesson 8.3)
and new Promise(…) (lesson 11.3) made values the same way. Map,
Error and Promise are classes, written by the people who made
JavaScript, and new builds an object from a class. That is where
new comes from.
A class is a blueprint for objects of one kind: it says which
properties every such object holds and which methods it can run. An
object built from a class is an instance of it: tally is an
instance of Map. The class keeps the data and the code that works
on it in one place, so the rules about a task list live with the
list. Now you write one.
Here is a class called TaskList, for a task list that has a name,
and two objects a program builds from it. Each object is shown by what
console.log prints for its name and its list:
What console. prints.
What console. prints.
Here is the whole program. Run it:
Lines 1 to 17 are the class; lines 19 and 20 build the two objects. The class has three kinds of parts, one section each below.
Lines 2 and 3 are the class's properties: the values every
TaskList holds. They are written like the lines of an interface
(lesson 6.4), a name, a colon and a type. Every object gets its own
boxes for them: home.name is "Home" and work.name is "Work".
You read them with a dot, as you would on any object (lesson 6.1), and
change them with = (lesson 6.2).
An interface only describes an object, and you build the object
yourself with { … }. A class builds its objects, so it has to give
every property its first value, and TypeScript checks that it does.
That is the constructor's job.
The constructor, lines 5 to 8, is a function inside the class
that runs once for every new. Its parameters are what new passes
in: new TaskList("Home") hands it "Home" as name. Inside it,
this is the new object being built. this.name = name puts the
parameter name into the object's property name. They are the same
word, but this.name belongs to the object and lives as long as it
does, while name alone is the parameter, a box that is gone when the
constructor ends.
Press Next step to watch new build home:
A property the constructor never fills stays undefined, and a
method that counts on it breaks quietly. Say TaskList had a count,
done: number;, that the constructor never set: this.done + 1 would
give NaN, "not a number". So TypeScript refuses such a class. Take
this.titles = []; out of the constructor above, and the check says,
with TS2564: Property 'titles' has no initializer and is not definitely assigned in the constructor. An "initializer" is a
first value written right on the property's line,
titles: string[] = [];, which is the other way to give it one.
Either way, every property has a value before anyone can use the
object.
add and count, lines 10 to 16, are the class's methods:
functions written inside the class, without the word function.
Every TaskList can run them, and you call them with a dot, as you
call tally.set: home.add("buy milk"). add gives nothing back,
so its return type is void (lesson 5.6); count gives back a
number.
A method is written once, in the class, yet each call works on one
object's data. That is this again: inside a method, this is the
object before the dot. Press Next step to follow three calls, or
let it play:
All 6 steps shown.
The name of a class is also a type, like the name of an interface:
function describe(list: TaskList) takes any task list, and
TypeScript knows it has a name, titles, add and count. And
instanceof, which you met in lesson 8.3, asks which class built a
value: home instanceof TaskList is true, just as
error instanceof Error is true for a value built by new Error.
A class is not a function you call, though. TaskList("Home")
without new is refused with TS2348: Value of type 'typeof TaskList' is not callable. Did you mean to include 'new'? Here
typeof TaskList is TypeScript's name for the class itself, the
blueprint, while TaskList alone is the type of one object built from
it.
Two lists, built from one class. Read the code and decide what the last line prints.
Predict
What does this program print?
this.Inside the class, titles is declared right at the top. So you
write it the way you would use any box.
Common mistake
Using a property by its bare name inside a method
Line 3 is not a box of its own: each object gets a titles box, so
a method has to say which object's it means. There is no titles on
its own, only home's, work's, or the one the method was called
on.
The error calls this.titles an "instance member": a property or a
method that belongs to each object of the class. It is not the member
of a union from lesson 7.1.
Cannot find name 'titles'. Did you mean the instance member 'this.titles'?
The fix
Reach it through the object the method works on, this:
Inside a class, every property is written with this. in front, in
the constructor and in every method. When TypeScript says it cannot
find a name and suggests this. with it (TS2663), take the
suggestion.
TaskKit's list gets its class now: TaskStore. A TaskStore holds
the Map of tasks and the limit, and it loads, adds and saves its
tasks itself.
Turn store.ts into a class
In ~/projects/taskkit, replace the whole of store.ts with this:
export goes in front of a class as it does in front of a function
(lesson 9.1). The constructor starts every store with an empty Map
and the limit it is given. add holds the four outcomes the add case
had in index.ts: an empty task, a twin, no room, and the task added.
Each else if became an if that returns its message (the early
return of lesson 5.6), so the first rule that matches ends the call.
That is why the room check is reversed: the old
else if (tasks.size < limit) added the task, while
if (this.tasks.size >= this.limit) returns No room for: …, and the
task is added on the last lines, only when no rule stopped it. Instead
of printing, add gives the message back, and a test can check it.
load and save are the old loadTasks and saveTasks:
load fills the store's own Map instead of making one, and save
writes it. A method can be async like any function (lesson 11.4).
Use the store in index.ts
In index.ts, change the line that imports from ./store.ts to:
Then change the two lines const limit = 5; and
const tasks = await loadTasks(); to these two:
Replace the whole add case, from case "add": to its break;,
with this one:
Last, change printSummary( and
printList(tasks); at the end of the try to:
Test the store
Make store.test.ts with two tests: one for add, and one that
proves two stores do not share their tasks.
The tests never call save, so they write no file.
index.ts still reaches into the store from outside, in
store.tasks.size and store.limit, and nothing stops a line there
from changing store.tasks without going through add. Keeping the data
inside the object is the next lesson's job.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Each one is checked in your browser: two errors to fix, one class to write, and one question about when a constructor runs.
Recap · 3 questions
Check yourself
What is the difference between a class and an object?
Check yourself
In this.name = name, what is the name on the right?
Check yourself
Inside home.add("buy milk"), what is this?
0 of 0 answered.
Cheat sheet
Classes: properties, constructors, and methods
What things are
| Word | What it means |
|---|---|
| Class | A blueprint: what each object holds and can do |
| Object, instance | One thing built from a class with new |
| Property | A value every object holds, each its own |
| Constructor | Runs once for every new to fill the object |
| Method | A function in the class, called with a dot |
this | The new object, or the object before the dot |
Code
| Write | To |
|---|---|
class TaskList { … } | Write a blueprint called TaskList |
name: string; | Declare a property and its type |
titles: string[] = []; | Declare it with a first value |
constructor(name: string) | Take what new passes in |
this.name = name; | Put the parameter into the object |
add(title: string): void | Write a method |
new TaskList("Home") | Build one object from the class |
home.add("buy milk") | Run a method on home |
list: TaskList | Use the class as a type |
When TypeScript refuses
| Error | What it means |
|---|---|
| TS2564 | The constructor leaves a property without a value |
| TS2663 | A property used without this. in front |
You can now write a class: its properties, a constructor that fills
each new object through this, and methods that work on the object
before the dot. You know that Map, Error and Promise are
classes too, and TaskKit's list is an object of its own, a
TaskStore.
Next is private, #private, and readonly: TypeScript privacy
vs JavaScript privacy, where TaskStore keeps its Map to itself,
and TypeScript points at every line outside the class that still
reaches in.
Before you move on, give TaskStore a method of your own:
has(title: string): boolean, which answers whether a task with that
title is on the list (trim it and lower-case it, as add builds its
key). Try it in index.ts with a console.log, check, run, and take
the line out again.
Check, run and test
Delete tasks.json in VS Code first, so the list starts empty. Then:
npm run check
npm start add "buy milk" "call Mom" "buy milk"The check prints only its two > lines. These are the lines under
TaskKit's banner:
Added: Buy milk
Added: Call Mom
Already on the list: Buy milk
2 tasks added, room for 3 more
List 40% full
Your list, A to Z:
#1 [todo] Buy milk, due: not set
#2 [todo] Call Mom, due: not setThe same lines as before the change: nobody using TaskKit can tell. What changed is where the code lives. Run the tests too:
npm testThey end with ℹ pass 13 and ℹ fail 0: the eleven from before and
the two new ones.
| TS2348 | A class called without new |
How often the constructor runs
TaskList is the class from this lesson. How many times does its
constructor run in this program?
const home = new TaskList("Home");
const work = new TaskList("Work");
const same = home;
home.add("buy milk");
same.add("call Mom");
work.add("send report");class TaskList {
name: string;
titles: string[];
constructor(name: string) {
this.name = name;
this.titles = [];
}
add(title: string): void {
this.titles.push(title);
}
count(): number {
return this.titles.length;
}
}class TaskList {
name: string;
titles: string[];
constructor(name: string) {
this.name = name;
this.titles = [];
}
add(title: string): void {
this.titles.push(title);
}
count(): number {
return this.titles.length;
}
}
const home = new TaskList("Home");
const work = new TaskList("Work");
home.add("buy milk");
home.add("call Mom");
work.add("send report");
console.log(home.name, home.titles);
console.log(work.name, work.titles);class TaskList {
name: string;
titles: string[];
constructor(name: string) {
this.name = name;
this.titles = [];
}
add(title: string): void {
this.titles.push(title);
}
count(): number {
return this.titles.length;
}
}
const home = new TaskList("Home");
const work = new TaskList("Work");
home.add("buy milk");
home.add("call Mom");
console.log(work.count());class TaskList {
name: string;
titles: string[];
constructor(name: string) {
this.name = name;
this.titles = [];
}
add(title: string): void {
titles.push(title);
}
} add(title: string): void {
this.titles.push(title);
}import { existsSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import type { Task } from "./tasks.ts";
import { capitalize, tasksFromJson, tasksToJson } from "./tasks.ts";
const file = "tasks.json";
export class TaskStore {
tasks: Map<string, Task>;
limit: number;
constructor(limit: number) {
this.tasks = new Map<string, Task>();
this.limit = limit;
}
add(title: string): string {
const tidyTask = title.trim();
const newTask = capitalize(tidyTask);
const key = newTask.toLowerCase();
const twin = this.tasks.get(key);
if (tidyTask === "") {
return "Skipped an empty task";
}
if (twin !== undefined) {
return `Already on the list: ${twin.title}`;
}
if (this.tasks.size >= this.limit) {
return `No room for: ${newTask}`;
}
this.tasks.set(key, {
id: this.tasks.size + 1,
title: newTask,
status: "todo",
});
return `Added: ${newTask}`;
}
async load(): Promise<void> {
if (!existsSync(file)) {
return;
}
const text = await readFile(file, "utf8");
for (const task of tasksFromJson(text)) {
this.tasks.set(task.title.toLowerCase(), task);
}
}
async save(): Promise<void> {
await writeFile(file, tasksToJson(this.tasks));
}
}import { TaskStore } from "./store.ts";const store = new TaskStore(5);
await store.load(); case "add":
for (const title of command.titles) {
console.log(store.add(title));
}
if (store.tasks.size === 0) {
console.log(
`Add what? Try: npm start add "buy milk"`
);
}
await store.save();
break; printSummary(store.tasks.size, store.limit);
printList(store.tasks);import { test } from "node:test";
import assert from "node:assert/strict";
import { TaskStore } from "./store.ts";
test("add puts a new task on the list", () => {
const store = new TaskStore(5);
assert.equal(store.add("buy milk"), "Added: Buy milk");
assert.equal(store.tasks.size, 1);
});
test("each TaskStore has a list of its own", () => {
const home = new TaskStore(5);
const work = new TaskStore(5);
home.add("buy milk");
assert.equal(work.tasks.size, 0);
});class TaskList {
name: string;
titles: string[];
constructor(name: string) {
this.name = name;
this.titles = [];
}
}
const home = new TaskList("Home");
console.log(home);The file reaches new TaskList("Home").
new makes a new object, its properties still undefined, and calls
the constructor: the object is this, and "Home" is name.
this.name = name puts "Home" into the new object's own name.
this.titles = [] gives the object an empty list of its own.
The constructor is done. Its card comes off, and new hands the
filled object to home.
Node prints the object with its class's name in front.
PrintsTaskList { name: 'Home', titles: [] }Give every property a value
TypeScript refuses this class with Property 'done' has no initializer and is not definitely assigned in the constructor. Fix
it so that every new list starts with nothing done, and the program
prints Home: 1 done.
Loading the editor…
Build the basket
This program should put two things in a basket and print 2, but
TypeScript refuses line 13. Fix it.
Loading the editor…
Write a habit tracker
Write a class Habit so the lines under it print Drink water: 2 days and then Walk: 3 days. A habit has a name, given to new,
and a number of days, which starts at 0. markDone() adds one day,
and report() gives back the line to print.
Loading the editor…