private, #private, and readonly: TypeScript privacy vs JavaScript privacy
Keep a class’s data to itself with private or #, mark what never changes with readonly, and see which lock only TypeScript checks and which one Node keeps too. Then TaskKit’s TaskStore locks its tasks away.
TypeScript
Fundamentals
`private`, `#private`, and `readonly`: TypeScript privacy vs JavaScript privacy. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson TaskKit's list became one object,
store, and its four rules moved into add. Yet nothing makes anyone
use add. Any line of index.ts can write store.tasks.set(…) and
put a sixth task on a list of five, or a second "Buy milk", because
tasks is open to every line that has store. The rules are there,
and so is the way around them.
A house has a front door, and rooms that belong to the family. A
guest comes in through the door and goes where the family takes
them; nobody breaks through a wall into the bedroom. A class can mark
its rooms the same way. By the end of this lesson, TaskStore's
Map will be a room only its own methods enter, limit will be read
but never changed, and you will know which of TypeScript's two ways
to lock a room still holds while TaskKit runs.
Public and private parts
Every property and method you wrote in the last lesson is
public: any code that has the object may read it, change it or
call it. That is right for add, which is the way in, and wrong for
the Map behind it.
A private part is one that only the class's own code may use:
its constructor and its methods. Code outside the class goes through
the public methods, and the methods decide what happens to the data.
Here is TaskStore as it will be at the end of this lesson, with its
private room marked, and the two ways index.ts could try to get in:
store.ts
export class TaskStore {#tasks: Map<string, Task>; readonly limit: number; add(title: string): string {…} count(): number {…} list(): Task[] {…}}
Private
The class: public rooms and a private one
Does: Public: limit and every method, for any code
Never: #tasks is reached only by the class's own methods
Outside code comes in through the methods, never into #tasks
The {…} stands for each method's body, which you will write at the
end, and load and save, unchanged from the last lesson, are left
out of the picture. The # in front of tasks is what makes it
private, and readonly (lesson 6.2) is what keeps limit from
changing: the next sections explain both. TypeScript has two ways to
make a part private, and they are not the same lock.
Two ways to say private
The first is the word private in front of a property. Here
titles gets it, and line 11 reads the list from outside the class.
Run it:
list.tsts
class TaskList { private titles: string[] = []; add(title: string): void { this.titles.push(title); }}const home = new TaskList();home.add("buy milk");console.log(home.titles);
TypeScript refuses line 11 with TS2341: Property 'titles' is private and only accessible within class 'TaskList'. Line 5 is fine, because
add is the class's own code. (titles gets its first value on its
own line, as in the last lesson, so this class needs no constructor:
new TaskList() builds the object and fills titles with [].)
The second way is a # at the start of the name: #titles. The
# is part of the name, so it is written everywhere the property is
used, inside the class too:
list.tsts
class TaskList { #titles: string[] = []; add(title: string): void { this.#titles.push(title); }}const home = new TaskList();home.add("buy milk");console.log(home.#titles);
Line 11 is refused again, this time with TS18013: Property '#titles' is not accessible outside class 'TaskList' because it has a private identifier. A name that starts with # is a private name, the
"#private" of this lesson's title, and that is the "private
identifier" the message means.
So far the two look the same. The difference is who keeps them.
Who keeps the lock while the code runs
private is TypeScript's word: like a type, it is there only for the
check, and Node strips it out before it runs the file (lessons 7.6 and
8.2). #titles is JavaScript's own, and Node keeps it. Switch between
the two versions of list.ts, and press Next step to walk through
each, or let it play:
Yourcode
TypeScript
Node
Screen
Your code: list.tslist.tslist.ts
TypeScript: TS2341: titles is privateTS2341:titlesisprivateTS2341:titlesisprivate
npm run check reads every line and refuses line 11: titles
is private to TaskList.
node list.ts never runs the check. It strips the types,
private with them, and runs every line.
[ 'buy milk' ]: the private list is printed, as if private
had never been written.
TypeScript refuses both; Node refuses only #titles
All 4 steps shown.Step 1 of 4: Your code: list.tsStep 2 of 4: TypeScript: TS2341: titles is privateStep 3 of 4: Node: strips private, runsStep 4 of 4: Screen: list printed
All 4 steps shown.
Yourcode
TypeScript
Node
Screen
Your code: list.tslist.tslist.ts
TypeScript: TS18013: outside its classTS18013:outsideitsclassTS18013:outsideitsclass
Node: refuses the filerefusesthefilerefusesthefile
Screen: list not printedlistnotprintedlistnotprinted
Time
Line 11 reads the list from outside the class.
npm run check refuses line 11 too: #titles is not
accessible outside TaskList.
#titles is JavaScript, so Node keeps it, and stops with a
SyntaxError before any line runs.
The list never reaches the screen, only Node's error: the list
stays inside its class.
TypeScript refuses both; Node refuses only #titles
All 4 steps shown.Step 1 of 4: Your code: list.tsStep 2 of 4: TypeScript: TS18013: outside its classStep 3 of 4: Node: refuses the fileStep 4 of 4: Screen: list not printed
All 4 steps shown.
The page checks before it runs, so it can never show Node running
this file. Try that in your own terminal. In ~/projects/taskkit,
make a file list.ts with the first version above, the one with
private titles. Then check it, and run it with Node alone:
bash
npm run checknode list.ts
The check refuses line 11, as the page did. The message is one long
line in your terminal, broken here to fit the page:
What npm run check printstext
> check> tsclist.ts:11:18 - error TS2341: Property 'titles' is private and onlyaccessible within class 'TaskList'.11 console.log(home.titles); ~~~~~~Found 1 error in list.ts:11
Node runs the file anyway and prints the private list:
What node list.ts printstext
[ 'buy milk' ]
Now change list.ts to the #titles version: #titles on lines 2,
5 and 11. Run node list.ts again. This time Node stops before the
first line runs. The output starts like this, with the folder of your
own TaskKit in the first line:
The first lines of the outputtext
file:///Users/ana/projects/taskkit/list.ts:11console.log(home.#titles); ^SyntaxError: Private field '#titles' must be declared in an enclosing class
file:///C:/Users/ana/projects/taskkit/list.ts:11console.log(home.#titles); ^SyntaxError: Private field '#titles' must be declared in an enclosing class
file:///home/ana/projects/taskkit/list.ts:11console.log(home.#titles); ^SyntaxError: Private field '#titles' must be declared in an enclosing class
More lines follow: the at lines of lesson 1.5 and your Node version.
The last line of the block says what went wrong: SyntaxError: Private field '#titles' must be declared in an enclosing class. A
SyntaxError means the text is not shaped like code Node can run
(lesson 1.5): for Node, a private name written outside its class is
exactly that. ("Field" is JavaScript's word for a property declared in
a class.) Delete list.ts when you are done, so it does not stay in
TaskKit.
Both locks have their place. private is enough when every run is
checked first, and you will meet it in a lot of TypeScript code.
# holds even when nobody checks, and TaskKit runs with npm start,
which is node index.ts with no check in front. So TaskKit uses #.
readonly in a class
readonly works in a class as it does in an object type (lesson
6.2): the property can be read, but never changed after it gets its
value. A class gives it that value on its own line or in the
constructor, and from then on nothing may change it, not even the
class's own methods. Run this:
limit.tsts
class TaskStore { readonly limit: number; constructor(limit: number) { this.limit = limit; } grow(): void { this.limit = this.limit + 1; }}const store = new TaskStore(5);console.log(store.limit);
Line 5 is allowed: the constructor is filling the new object. Line 9
is refused with TS2540, Cannot assign to 'limit' because it is a read-only property., and so would be store.limit = 10; outside the
class. Reading it, as line 14 does, is always allowed, so limit can
stay public.
readonly is not privacy, though. Like const (lesson 6.7), it
locks what the box holds. For a Map or a list, the box holds an
arrow, so the Map at the end of the arrow can still change.
Bad — readonly keeps the arrow,
and a line outside adds a task without going through add.
ts
class TaskStore { readonly tasks = new Map<string, string>(); add(title: string): void { this.tasks.set(title.toLowerCase(), title); } count(): number { return this.tasks.size; }}const store = new TaskStore();store.tasks.set("walk dog", "Walk dog");console.log(store.count());
Good — #tasks is out of reach,
so the only way to add a task is add.
ts
class TaskStore { #tasks = new Map<string, string>(); add(title: string): void { this.#tasks.set(title.toLowerCase(), title); } count(): number { return this.#tasks.size; }}const store = new TaskStore();store.add("Walk dog");console.log(store.count());
Both print 1, and both pass the check. In the first, line 14 never
went through add, so whatever rules add holds never ran: in
TaskKit, nothing would stop a sixth task or a second "Buy milk". In
the second, store.tasks does not exist, and add is the only way
in.
Predict before you run
This list has one property of each kind. JSON.stringify (lesson
12.1) writes an object out as JSON (JavaScript Object Notation, data
written as text). Decide what it writes for home.
You make tasks private by renaming it to #tasks, and fix the line
that declares it. The methods still say this.tasks.
Common mistake
Leaving out the # inside the class
ts
class TaskStore { #tasks = new Map<string, string>(); add(title: string): void { this.tasks.set(title.toLowerCase(), title); }}
#tasks and tasks are two different names, as different as tasks
and task. The class has only #tasks, so this.tasks names
something that does not exist.
Property 'tasks' does not exist on type 'TaskStore'. Did you mean '#tasks'?
When you turn a property into a private name, change every place that
uses it, and let the check find the ones you missed. Inside the class
it says TS2551 with Did you mean '#tasks'?; outside, where #tasks
cannot be named, it says only that tasks does not exist (TS2339).
TaskKit: the store keeps its tasks
Now TaskStore locks its room. Its Map becomes #tasks, limit
becomes readonly, and two public methods let index.ts read what
it needs: count(), how many tasks there are, and list(), the
tasks themselves.
1
Lock the store's data
In ~/projects/taskkit, replace the whole of store.ts with this.
If you kept the has method from the end of the last lesson, put it
back after list, with this.#tasks inside:
store.tsts
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>; readonly 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}`; } count(): number { return this.#tasks.size; } list(): Task[] { return [...this.#tasks.values()]; } 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)); }}
Every this.tasks is now this.#tasks; add, load and save do
what they did. list gives back a new list made from the Map's
values (lesson 10.1), not the Map itself. If it handed out
this.#tasks, the caller would hold an arrow to the very Map
(lesson 6.7), and the # would guard nothing. The copy stops anyone
from adding tasks to the store or taking them out. The tasks in it are
still the store's own objects, as with any copy made with ...
(lesson 6.8), so a caller that changes a task's title changes it in
the store too.
2
Let the check find every line that reaches in
Run the check:
bash
npm run check
Each message is one long line in your terminal, broken here to fit the
page:
Outputtext
> check> tscindex.ts:32:17 - error TS2339: Property 'tasks' does not exist ontype 'TaskStore'.32 if (store.tasks.size === 0) { ~~~~~index.ts:56:22 - error TS2339: Property 'tasks' does not exist ontype 'TaskStore'.56 printSummary(store.tasks.size, store.limit); ~~~~~index.ts:57:19 - error TS2339: Property 'tasks' does not exist ontype 'TaskStore'.57 printList(store.tasks); ~~~~~store.test.ts:8:22 - error TS2339: Property 'tasks' does not exist ontype 'TaskStore'.8 assert.equal(store.tasks.size, 1); ~~~~~store.test.ts:14:21 - error TS2339: Property 'tasks' does not exist ontype 'TaskStore'.14 assert.equal(work.tasks.size, 0); ~~~~~Found 5 errors in 2 files.Errors Files 3 index.ts:32 2 store.test.ts:8
That is every line outside the class that still reaches into the
Map. The store has no tasks any more, only #tasks, which code
outside cannot even name. The table at the end counts them: three in
index.ts, two in store.test.ts.
3
Go through the door in index.ts
In index.ts, in the add case, change the line
if (store.tasks.size === 0) { to:
index.tsts
if (store.count() === 0) {
At the end of the try, change these two lines,
printSummary(store.tasks.size, store.limit); and
printList(store.tasks);, to:
printList now gets a list of tasks rather than a Map. In
print.ts, its first two lines take a Map and turn its values into
a list with [...tasks.values()]; change them to these, which take
the list as it comes:
print.tsts
export function printList(tasks: Task[]): void { const byName = tasks.toSorted((a, b) =>
4
Test through the door too
Replace store.test.ts with this. The first two tests count with
count(), and the third proves that list() hands out a copy:
store.test.tsts
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.count(), 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.count(), 0);});test("pushing onto list() leaves the store alone", () => { const store = new TaskStore(5); store.add("buy milk"); store.list().push({ id: 2, title: "Walk dog", status: "todo" }); assert.equal(store.count(), 1);});
5
Check, run and test
Delete tasks.json in VS Code first, so the list starts empty. Then:
The check prints only its two > lines. These are the lines under
TaskKit's banner, the same as before the change:
What TaskKit printstext
Added: Buy milkAdded: Call MomAlready on the list: Buy milk2 tasks added, room for 3 moreList 40% fullYour list, A to Z:#1 [todo] Buy milk, due: not set#2 [todo] Call Mom, due: not set
Run the tests too:
bash
npm test
They end with ℹ pass 14 and ℹ fail 0: the thirteen from before
and the new one.
TaskKit's list now lives in one place, and the only ways to put tasks
on it are the store's own methods, add and load. That is the
module's project step done: task storage in a class, with private data and
public methods.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser: two to fix, one class to write,
and one question about which lock Node keeps.
Exercise · Fix the error
Count through the door
TypeScript refuses line 16 with Property 'titles' is private and only accessible within class 'TaskList'. Fix it without taking
private away, so the program prints 2.
Loading the editor…
Exercise · Write the code
Write a wallet
Write a class Wallet so the lines under it print Spent 5, 15 left, Not enough money and 15. new Wallet(20) starts with 20
in it. spend(amount) takes the amount out and gives back a line like
Spent 5, 15 left; when the wallet holds less than the amount, it
takes nothing out and gives back Not enough money. balance() gives
back what is left. Keep the money in a private name, #money, so no
code outside the class can change it.
Loading the editor…
Exercise · Read the code
Which line Node refuses
TaskStore below has one property of each kind. Each answer is one
line, added on its own under the class, and the file is run with
node alone, with no check first. Which line does Node itself
refuse?
ts
class TaskStore { #tasks = new Map<string, string>(); private size = 0; readonly limit = 5;}const store = new TaskStore();
Exercise · Fix the error
Hand out a copy
This program prints 2: line 19 added a task without going through
add, although #titles is private, and TypeScript says nothing.
Change list so the program prints 1.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
Every run is checked first. Is private enough?
Check yourself
What is the # in #titles to JavaScript?
Check yourself
home.titles is readonly. Which line passes the check?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
private, #private, and readonly
What things are
Word
What it means
Public
Any code with the object may use it; the default
Private
Only the class's own code may use it
private
TypeScript's lock: checked, then stripped
Private name, #titles
JavaScript's lock: Node keeps it
readonly
Set on its own line or in the constructor, never after
Code
Write
To
private titles: string[]
Make a property private to the check
#titles: string[] = [];
Make a property private to JavaScript
this.#titles
Use it inside the class, # included
readonly limit: number;
Let anyone read it, nobody change it
count(): number
Let outside code read through a method
[...this.#titles]
Hand out a copy, never the list itself
When it is refused
Error
What it means
TS2341
A private property used outside its class
TS18013
A private name used outside its class
TS2551
this.tasks where the name is #tasks
TS2540
A readonly property given a new value
SyntaxError
Node: a private name written outside its class
Which lock
Use
When
#
The code may run unchecked, as with npm start
private
Every run is checked first
readonly
A value set once and only read after
Where to go next
You can now keep a class's data to itself: private when the check
is enough, # when the lock must hold while the code runs, and
readonly for what is set once. TaskKit's TaskStore holds its
tasks in #tasks, and index.ts reaches them only through add,
count and list.
Next is When to use classes, and when functions and objects are
enough, where you weigh TaskStore against the functions and plain
objects TaskKit used before, and learn when a class is worth it.
Before you move on, try the # lock on TaskKit itself. Add
console.log(store.#tasks.size); after await store.load(); in
index.ts. Run npm run check and read what it says, then run
npm start help and find Node's SyntaxError among the lines it
prints. Take the line out again.