Classes
Overview
JavaScript classes bundle data and behaviour: a bank account with its balance and its deposit method, a shopping cart with its lines and its total. TypeScript adds types to every field, parameter and return value, plus a few class-specific features covered in the next two lessons. If you’ve used classes in JavaScript, almost everything carries over.
Fields
In TypeScript, fields are declared in the class body with their types:
class BankAccount {
owner: string;
balance = 0; // type inferred from the initialiser
history: number[] = [];
closedAt: Date | null = null;
constructor(owner: string) {
this.owner = owner;
}
}Using a field that wasn’t declared is an error, just like a missing property on an object type.
Initialisation is checked
With strict on, every field must definitely be given a value — in its declaration or in the constructor:
class User {
name: string;
// error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.
}Fix it by initialising the field, assigning it in the constructor, making it optional (name?: string), or — if a framework sets it later and you’re certain — using the definite assignment assertion name!: string (with the same caution as the ! operator).
Constructors
The constructor is typed like any function, including optional and default parameters:
class Timer {
readonly label: string;
readonly startedAt: number;
constructor(label = "timer", now: number = Date.now()) {
this.label = label;
this.startedAt = now;
}
}
const t = new Timer("build");Methods, getters and setters
class BankAccount {
balance = 0;
deposit(amount: number): void {
if (amount <= 0) throw new RangeError("Deposit must be positive");
this.balance += amount;
}
get isEmpty(): boolean {
return this.balance === 0;
}
get formatted(): string {
return `$${this.balance.toFixed(2)}`;
}
}
const acc = new BankAccount();
acc.deposit(50);
acc.isEmpty; // false — getters are read like propertiesA getter without a setter is read-only from outside: acc.isEmpty = true is an error. A setter’s parameter type must accept what the getter returns.
Returning this
A method that returns this allows chaining, and the type stays precise even in subclasses:
class QueryBuilder {
private parts: string[] = [];
where(condition: string): this {
this.parts.push(condition);
return this;
}
}
new QueryBuilder().where("age > 18").where("active = 1");Static members
static fields and methods belong to the class itself — useful for factories, counters and constants:
class Temperature {
static readonly ABSOLUTE_ZERO = -273.15;
static fromFahrenheit(f: number): Temperature {
return new Temperature((f - 32) * (5 / 9));
}
readonly celsius: number;
constructor(celsius: number) {
this.celsius = celsius;
}
}
Temperature.fromFahrenheit(212).celsius; // 100A class is a value and a type
class BankAccount { … } creates two things with the same name:
- a value: the constructor function, used with
newand for static members; - a type: the shape of its instances, used in annotations.
function audit(account: BankAccount) { … } // the type
const acc = new BankAccount(); // the valueBecause TypeScript is structural, the type BankAccount is just “objects with these public members” — a plain object with the same shape also fits. (Classes with private or #private members are the exception: only real instances fit, because outsiders can’t have those members.)
Generic classes
Classes take type parameters like functions and type aliases (Generic types):
class TypedEventTarget<Events extends Record<string, unknown>> {
private listeners: { [E in keyof Events]?: ((payload: Events[E]) => void)[] } = {};
on<E extends keyof Events>(event: E, listener: (payload: Events[E]) => void): void {
(this.listeners[event] ??= []).push(listener);
}
emit<E extends keyof Events>(event: E, payload: Events[E]): void {
for (const listener of this.listeners[event] ?? []) listener(payload);
}
}
const bus = new TypedEventTarget<{ login: { user: string }; logout: undefined }>();
bus.on("login", ({ user }) => console.log(`${user} logged in`));
bus.emit("login", { user: "Asha" });Parameter properties — and why we avoid them
You’ll often see this shorthand in TypeScript code:
class User {
constructor(public name: string, private email: string) {}
}A modifier on a constructor parameter declares and assigns the field in one go. It’s convenient, but it’s one of the few TypeScript features that generates code (the this.name = name assignments), so Node’s type stripping can’t run it and erasableSyntaxOnly reports it:
error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.In this course we declare fields and assign them explicitly. In projects compiled by tsc or a full transpiler, parameter properties are fine — and frameworks like Angular and NestJS use them heavily.
Remember: declare every field with its type, initialise it, type methods like functions — and remember the class name is both a constructor and a type.
A shopping cart class
Write a ShoppingCart class. Fields: a readonly currency (string, set in the constructor) and a lines Map from SKU to { product: Product; quantity: number }. Methods: add(product: Product, quantity = 1): this (adds to an existing line, returns this so calls can be chained), remove(sku: string): boolean, and clear(): void. Getters: itemCount (total quantity) and total (sum of price × quantity). A static method fromList(products: Product[], currency: string): ShoppingCart creates a cart with one of each product. Use it: add two lamps and a notebook with chained calls, add one more lamp, print the item count and total formatted as INR 53.48, remove the notebook, and print again.
type Product = { sku: string; name: string; price: number };
const lamp: Product = { sku: "LMP-01", name: "Desk Lamp", price: 14.99 };
const notebook: Product = { sku: "NB-A5", name: "Notebook", price: 8.51 };
class ShoppingCart {
// fields, constructor, methods, getters, static fromList
}type Product = { sku: string; name: string; price: number };
const lamp: Product = { sku: "LMP-01", name: "Desk Lamp", price: 14.99 };
const notebook: Product = { sku: "NB-A5", name: "Notebook", price: 8.51 };
class ShoppingCart {
readonly currency: string;
private lines = new Map<string, { product: Product; quantity: number }>();
constructor(currency: string) {
this.currency = currency;
}
static fromList(products: Product[], currency: string): ShoppingCart {
const cart = new ShoppingCart(currency);
for (const product of products) cart.add(product);
return cart;
}
add(product: Product, quantity = 1): this {
const line = this.lines.get(product.sku);
if (line) {
line.quantity += quantity;
} else {
this.lines.set(product.sku, { product, quantity });
}
return this;
}
remove(sku: string): boolean {
return this.lines.delete(sku);
}
clear(): void {
this.lines.clear();
}
get itemCount(): number {
let count = 0;
for (const line of this.lines.values()) count += line.quantity;
return count;
}
get total(): number {
let sum = 0;
for (const { product, quantity } of this.lines.values()) sum += product.price * quantity;
return sum;
}
}
const cart = new ShoppingCart("INR");
cart.add(lamp, 2).add(notebook);
cart.add(lamp);
console.log(cart.itemCount, `${cart.currency} ${cart.total.toFixed(2)}`); // 4 INR 53.48
cart.remove("NB-A5");
console.log(cart.itemCount, `${cart.currency} ${cart.total.toFixed(2)}`); // 3 INR 44.97
const quick = ShoppingCart.fromList([lamp, notebook], "EUR");
console.log(quick.itemCount, quick.total.toFixed(2)); // 2 23.50Summary
- Declare fields with types in the class body; with strict checks, every field must be initialised in its declaration or the constructor.
- Methods and getters are typed like functions; returning
thisenables safe method chaining. staticmembers belong to the class itself, not to instances.- A class is both a value (the constructor) and a type (its instances) — and types are still structural.
- Parameter properties (
constructor(private x: T)) generate code, soerasableSyntaxOnlyrejects them — assign fields explicitly.