Classes in TypeScript

In a TypeScript class, properties are declared with their types. public is usable from anywhere (the default), private only inside that class, protected…

In the JavaScript track you already built classes: blueprints for objects, with a constructor that stores data on this and methods that read it. TypeScript adds two things: a type for every property, and access modifiers that decide where a property may be used from. Picture an office: the lobby is open to anyone, the archive door has a "Staff only" sign on it, and the safe is properly locked. A sign on a door only works while there's a guard to tell people off, and the guard is TypeScript, checking your code.

Typed properties and access modifiers

class Animal {
  public name: string
  private sound: string

  constructor(name: string, sound: string) {
    this.name = name
    this.sound = sound
  }

  speak(): string {
    return this.name + " says: " + this.sound
  }
}

Who may touch what

Now add a subclass Cat, then code outside the class that reads and changes sound:

class Cat extends Animal {
  showOff(): string {
    return "My sound is " + this.sound
  }
}

const cat = new Cat("Cat", "Meow")
console.log(cat.speak())
console.log(cat.showOff())
console.log(cat.sound)
cat.sound = "Woof"
console.log(cat.speak())

Change the modifier in front of sound, and TypeScript judges every line that touches it:

Line touching sound public private protected readonly
inside Animal, method speak allowed allowed allowed allowed
in the subclass Cat, method showOff allowed ts(2341) allowed allowed
outside, reading cat.sound allowed ts(2341) ts(2445) allowed
outside, changing cat.sound = "Woof" allowed ts(2341) ts(2445) ts(2540)

Parameter properties: declare and fill in one go

Writing sound three times (declaration, parameter, this.sound = sound) gets tiring. The shortcut: put the access modifier straight on the constructor parameter.

class Animal {
  constructor(public name: string, private sound: string) {}

  speak(): string {
    return this.name + " says: " + this.sound
  }
}

Since TypeScript 5.8 there's an erasableSyntaxOnly option, for projects that run .ts just by deleting the types (for example Node.js running a .ts file directly). A parameter property needs extra code in the JavaScript (this.name = name), so with that option on it is rejected: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. ts(1294). In such a project, use the long version. The React, Vue and Vanilla TypeScript templates of npm create vite@latest also turn this option on, so the long version is the one to use in a new Vite project too.

private only exists while checking

Types and access modifiers are only used while TypeScript checks your code. When tsc turns it into JavaScript, they are all deleted. The long version and the parameter property both become the same JS:

class Animal {
    name;
    sound;
    constructor(name, sound) {
        this.name = name;
        this.sound = sound;
    }
    // speak() is still there, without ": string"
}

The word private is gone, and sound is an ordinary property. So the Cat program above, if its JS is run despite the errors, prints Cat says: Meow, My sound is Meow, Meow, then Cat says: Woof. cat.sound prints Meow, and changing it to Woof works too. private is a "Staff only" sign: TypeScript tells you off in the editor, but the JavaScript locks nothing.

Need a real lock? Use JavaScript's own private field, which starts with #:

class Animal {
  #sound: string
  constructor(public name: string, sound: string) {
    this.#sound = sound
  }
}

implements and abstract classes

implements is a promise that the class matches the shape of an interface (from the Interface lesson). If class Robot implements CanSpeak forgets the method speak() its interface asks for, TypeScript rejects it: Class 'Robot' incorrectly implements interface 'CanSpeak'. ts(2420).

An abstract class is a class that may only be a parent. It can have abstract methods: methods with no body that every subclass must write.

abstract class Animal {
  constructor(public name: string) {}
  abstract speak(): string
}

class Cat extends Animal {
  speak(): string { return "Meow" }
}

new Cat("Cat").speak() // "Meow"
new Animal("Who") // error ts(2511)

⚠️ Why is sound undefined, or refused?

TL;DR: In a TypeScript class, properties are declared with their types. public is usable from anywhere (the default), private only inside that class, protected inside that class and its subclasses, and readonly can be read but only set in its declaration or the constructor. A parameter property, constructor(public name: string, private sound: string) {}, declares and fills in one go, as long as it has a modifier (and it's rejected when erasableSyntaxOnly is on). All these modifiers are only checked by TypeScript and vanish in JavaScript; the lock that's still there when the program runs is #field. implements promises an interface's shape, and an abstract class can't be newed and forces subclasses to write its abstract methods.

⚡ Typed properties and access modifiers

Write:

class Animal {
  public name: string
  private sound: string

  constructor(name: string, sound: string) {
    this.name = name
    this.sound = sound
  }
}

Meaning: In TypeScript, properties are declared first, with their types. public can be used from anywhere, private only inside this class, not even in a subclass. protected works in this class and its subclasses.

⚡ Declare and fill in one go

Write:

class Animal {
  constructor(public name: string, private sound: string) {}

  speak(): string {
    return this.name + " says: " + this.sound
  }
}

Meaning: An access modifier on a constructor parameter declares the property and fills it in one go, so the body can stay empty. The modifier is required: a parameter without one doesn't become a property, and you get Cat says: undefined.

In the exercise, the sentence has to be exactly Cat says: Meow, spaces and colon included.

⚡ private only exists while checking

Guess first: if the JavaScript runs anyway despite the error, what does cat.sound from outside the class print?

Meow. The word private is removed when it becomes JavaScript, so sound is just an ordinary property.

Meaning: private is a "Staff only" sign: TypeScript warns you in the editor, but the JavaScript locks nothing. Need a real lock? Use JavaScript's own private field, #sound, which stays guarded while the program runs.

What you will learn