Classes in TS

Typed Fields, Typed Methods, Typed Constructors

Classes in TS

TS classes look like JS classes — but every field, parameter, and return value can have a type. Plus a few new modifiers.

4 min read Level 1/5 #typescript#classes#oop
What you'll learn
  • Author a class with typed fields and methods
  • Type the constructor and assigned fields
  • Use class names as types

JS classes get types. TS adds a few extras — modifiers, abstracts, parameter properties — but the bones are the same.

A Typed Class

class Point {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

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

const a = new Point(0, 0);
const b = new Point(3, 4);
a.distanceTo(b);   // 5

Every field declares its type. The constructor declares its parameter types. Methods declare parameter and return types.

Field Initialization

Fields must be definitely assigned by the end of the constructor. TS will yell if not:

class User {
  name: string;   // ✗ Property 'name' has no initializer and is
                  // not definitely assigned in the constructor.
}

Fix: initialize inline, in the constructor, or mark optional.

class User {
  name: string = "";              // inline
  nickname?: string;              // optional
  email!: string;                 // "trust me, bro" assertion

  constructor(public id: string) {   // parameter property (next file)
    this.email = `${id}@example.com`;
  }
}

! after a field tells TS “I’ll set this — don’t check.” Use sparingly.

Class Names Are Types

function midpoint(a: Point, b: Point): Point {
  return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}

A class declaration introduces both a value (the constructor) and a type (the instance shape). Point as a type means “an instance of Point”.

Inheritance

class Animal {
  constructor(public name: string) {}
  speak(): string { return "..." }
}

class Dog extends Animal {
  speak(): string { return "woof" }
}

const d: Animal = new Dog("Rex");
d.speak();   // "woof"

Same extends. TS checks that the subclass conforms.

instanceof

function feed(x: Animal | string) {
  if (x instanceof Animal) {
    x.speak();   // x: Animal
  } else {
    console.log(x.toUpperCase());   // x: string
  }
}

instanceof is a narrowing check — TS knows that inside the branch, x is an Animal.

Up Next

Access modifiers — public, private, protected, and #.

Access Modifiers →