TExcelTAD
Home › TypeScript › TS Classes

TypeScript Classes

TypeScript classes are JavaScript classes with types added. You declare the type of every property, control who may access members with access modifiers, and let the compiler check that a class really implements the interfaces it promises to.

Typed properties and constructors

In strict mode every property must be declared and initialised — either where it is declared or in the constructor:

ts · try it yourself
class Counter {
  label: string;
  count = 0;                 // type inferred as number

  constructor(label: string) {
    this.label = label;
  }

  increment(step = 1): number {
    this.count += step;
    return this.count;
  }
}

const clicks = new Counter("clicks");
clicks.increment();
clicks.increment(5);
console.log(clicks.label, clicks.count);
clicks 6

Forget to initialise a property and the compiler complains:

ts · try it yourself
class Product {
  title: string;
  price: number;

  constructor(title: string) {
    this.title = title;
  }
}
main.ts(3,3): error TS2564: Property 'price' has no initializer and is not definitely assigned in the constructor.

Access modifiers

Modifier Accessible from
public (default) anywhere
protected the class and its subclasses
private only inside the class
readonly anywhere, but can only be assigned in the declaration or constructor
ts · try it yourself
class BankAccount {
  readonly owner: string;
  private balance = 0;

  constructor(owner: string) {
    this.owner = owner;
  }

  deposit(amount: number): void {
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

const acc = new BankAccount("Hoa");
acc.deposit(100);
acc.balance = 1_000_000;
acc.owner = "Mallory";
main.ts(20,5): error TS2341: Property 'balance' is private and only accessible within class 'BankAccount'.
main.ts(21,5): error TS2540: Cannot assign to 'owner' because it is a read-only property.

Note: private is a compile-time check only — the property still exists on the JavaScript object. If you need true runtime privacy, use JavaScript's #balance private fields, which TypeScript also supports.

Parameter properties

Declaring a property and assigning it from a constructor parameter is so common that TypeScript has a shortcut: put a modifier in front of the parameter.

ts · try it yourself
class Point {
  constructor(public readonly x: number, public readonly y: number) {}

  distanceTo(other: Point): number {
    return Math.hypot(other.x - this.x, other.y - this.y);
  }
}

const a = new Point(0, 0);
const b = new Point(3, 4);
console.log(a.distanceTo(b));
console.log(b);
5
Point { x: 3, y: 4 }

Implementing interfaces

implements tells the compiler to check that a class has everything an interface requires. It does not add any code; it is a contract.

ts · try it yourself
interface Shape {
  area(): number;
  describe(): string;
}

class Circle implements Shape {
  constructor(private radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2;
  }
  describe(): string {
    return `circle r=${this.radius}`;
  }
}

class Square implements Shape {
  constructor(private side: number) {}
  area(): number {
    return this.side ** 2;
  }
  describe(): string {
    return `square ${this.side}x${this.side}`;
  }
}

const shapes: Shape[] = [new Circle(1), new Square(2)];
for (const s of shapes) {
  console.log(s.describe(), "->", s.area().toFixed(2));
}
circle r=1 -> 3.14
square 2x2 -> 4.00

Inheritance, override and abstract classes

A class can extend one other class. Mark methods that replace a parent method with override — if the parent method is later renamed, the compiler flags the stale override. An abstract class cannot be instantiated and may declare abstract methods that subclasses must implement.

ts · try it yourself
abstract class Animal {
  constructor(protected nickname: string) {}
  abstract sound(): string;
  speak(): string {
    return `${this.nickname} says ${this.sound()}`;
  }
}

class Dog extends Animal {
  sound(): string {
    return "woof";
  }
  override speak(): string {
    return super.speak() + "!";
  }
}

class Cat extends Animal {
  sound(): string {
    return "meow";
  }
}

const pets: Animal[] = [new Dog("Rex"), new Cat("Mochi")];
pets.forEach((p) => console.log(p.speak()));
Rex says woof!
Mochi says meow

Trying new Animal("x") would fail with Cannot create an instance of an abstract class.

Test yourself

What does constructor(private id: number) {} do?

  1. Declares a private parameter only usable in the constructor
  2. Declares and assigns a private property id
  3. Makes the constructor private
  4. Nothing; it's invalid syntax

Which modifier allows access from subclasses but not from outside code?

  1. public
  2. private
  3. protected
  4. readonly

What does class A implements B add to the emitted JavaScript?

  1. Copies B's methods into A
  2. Nothing — it's only a compile-time check
  3. A runtime instanceof check
  4. A call to B's constructor