⊗tsSpOpSPO 15 of 37 menu

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:

class 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:

class 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:

class 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:

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

Let's change the salary for the first user:

user1.setSalary(2000);

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

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

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

console.log(User.salary); // 2000

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

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline