Static Properties in TypeScript

Let's look at how to access static properties inside objects.

Let's say we have the following class with a static property:

typescriptclass User {
  public name: string;
  public static salary: number = 1000;
  
  constructor(name: string) {
    this.name = name;
  }
}

Let's now make a method that outputs the total salary:

typescriptclass User {
  public name: string;
  public static salary: number = 1000;
  
  constructor(name: string) {
    this.name = name;
  }
  
  getSalary(): number {
    return User.salary; // we refer to the class name
  }
}

Let's now make a method that changes the total salary:

typescriptclass User {
  public name: string;
  public static salary: number = 1000;
  
  constructor(name: string) {
    this.name = name;
  }
  
  getSalary(): number {
    return User.salary;
  }
  
  setSalary(salary: number) {
    User.salary = salary;
  }
}

Static properties will be common to different objects. This means that when a property is changed in one object, it will change in the other. Let's check this.

Let's create two objects of our class:

typescriptlet user1: User = new User('john');
let user2: User = new User('eric');

Let's change the salary for the first user:

typescriptuser1.setSalary(2000);

Let's check that the salary has changed for the second user as well:

typescriptconsole.log(user2.getSalary()); // 2000

Let's check that the salary has also changed in the property of the class itself:

typescriptconsole.log(User.salary); // 2000
Задание 1

Add a static property university to the Student class. Infer this property without declaring an object.