Classes

Topic 1 of 3 in Classes7 min readIntermediateFree course

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.

Anatomy of a TypeScript class. class BankAccount { readonly owner: string; — a field with a type, readonly. balance = 0; — a field whose type is inferred. constructor(owner: string) { this.owner = owner; } — runs on new BankAccount(…). deposit(amount: number): void { this.balance += amount; } — a method. get isEmpty(): boolean { return this.balance === 0; } — a getter, used as acc.isEmpty. A class creates a value (the constructor, used with new) and a type with the same name (its instances).

Fields

In TypeScript, fields are declared in the class body with their types:

TypeScript
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:

TypeScript
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:

TypeScript
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

TypeScript
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 properties

A 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:

TypeScript
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:

TypeScript
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;   // 100

A class is a value and a type

class BankAccount { … } creates two things with the same name:

  • a value: the constructor function, used with new and for static members;
  • a type: the shape of its instances, used in annotations.
TypeScript
function audit(account: BankAccount) { … }   // the type
const acc = new BankAccount();               // the value

Because 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):

TypeScript
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:

TypeScript
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:

Text
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.

Exercise

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.

TypeScript
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
}

Summary

  • 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 this enables safe method chaining.
  • static members 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, so erasableSyntaxOnly rejects them — assign fields explicitly.