Curriculum
Course: TypeScript
Login
Text lesson

TS Classes

TypeScript enhances JavaScript classes by adding type annotations and visibility modifiers.

Members: Types

The members of a class (properties and methods) are typed using type annotations, much like variables.

Example

class Person {
  name: string;
}

const person = new Person();
person.name = “Jane”;

Members: Visibility

Class members can also have special modifiers that influence their visibility.

TypeScript has three main visibility modifiers:

  1. public (default): Allows access to the class member from anywhere.
  2. private: Restricts access to the class member to within the class itself.
  3. protected: Permits access to the class member within the class and any subclasses that inherit it, as discussed in the inheritance section below.

Example

class Person {
  private name: string;

  public constructor(name: string) {
    this.name = name;
  }

  public getName(): string {
    return this.name;
  }
}

const person = new Person(“Jane”);
console.log(person.getName()); // person.name isn’t accessible from outside the class since it’s private