Building Functionality With Classes

Access Modifiers

TypeScript gives you the ability to apply access modifiers to your class's properties or methods:

  • public

    • By default, all properties and methods have public access: the method and property can be accessed from anywhere any time.

  • private

    • Can only be called by other methods in that same class

  • protected

    • Can be called by others methods in the same class or child classes' methods

Please refer to the C# Intermediate notes to learn more!

Pro tip: An easy way to initialize fields in your constructor is to use the public modifier.

class Car {
  constructor(public color: string) {}
}

const car = new Car('red');
console.log(car.color); // red

Why Classes Matter

Just like interfaces, in TypeScript, classes are one of the main tools we use to ensure strong code reuse!

Last updated