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:
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:
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 |
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:
privateis a compile-time check only — the property still exists on the JavaScript object. If you need true runtime privacy, use JavaScript's#balanceprivate 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.
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.
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.
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?
- Declares a private parameter only usable in the constructor
- Declares and assigns a private property
id - Makes the constructor private
- Nothing; it's invalid syntax
Which modifier allows access from subclasses but not from outside code?
- public
- private
- protected
- readonly
What does class A implements B add to the emitted JavaScript?
- Copies B's methods into A
- Nothing — it's only a compile-time check
- A runtime instanceof check
- A call to B's constructor