1class Account {2 private balance = 0;3 constructor(public owner: string) {}4 deposit(amount: number): number {5 this.balance += amount;6 return this.balance;7 }8}9const ada = new Account("Ada");10ada.deposit(50);11console.log(ada.deposit(25));12const bob = new Account("Bob");13ada.balance = 1000;tsctype checker!adaownerbalancebobownerbalance>75"Ada"502575"Bob"TS
account.ts: the class (lines 1-8) and the code that uses it (lines 9-12)Objects: ada and bob, each with its own owner and balance (locked: private)Tokens: values hopping from a line of code into an object, and out to the consoleLeft: account.ts, a class Account and the code that uses it. Right: tsc, the type checker; two objects built from the class, ada and bob; and the console. new builds each object and the constructor fills it; deposit changes only the object before the dot, so ada's balance goes 0, 50, 75 while bob's stays 0. tsc rejects ada.balance = 1000; because balance is private, then erases private with the types. TypeScript's private is a "soft" private: it is only enforced during type checking, so plain JavaScript (or bracket access like ada["balance"]) can still reach the field at run time. JavaScript's own #private fields are enforced at run time.

The blueprint

  1. Lines 1 to 8 describe a bank account: the data each account holds and what it can do. A class is a blueprint. Writing it creates no account yet, just as a house plan is not a house.

Objects at run time

Checked, then erased

What happens

;; step 1/8 · blueprint
account.ts, lines 1-8
>  1  class Account {
   2    private balance = 0;
   3    constructor(public owner: string) {}
   4    deposit(amount: number): number {
   5      this.balance += amount;
   6      return this.balance;
   7    }
>  8  }

class Account { ... }  the blueprint
no object exists yet

TypeScript's private is a "soft" private: it is only enforced during type checking, so plain JavaScript (or bracket access like ada["balance"]) can still reach the field at run time. JavaScript's own #private fields are enforced at run time. The JavaScript shown is what tsc 5.9 writes with --target es2022. Older targets turn the class into a function with the method on Account.prototype; the program still prints 75.