Background:
Static properties and methods appeared in JavaScript classes starting from ES6; however, strict typing of these elements became possible thanks to TypeScript. In dynamic JavaScript, class static elements do not differ in type from instance elements, but TypeScript allows adding type safety and class structure considering static members.
Problem:
Static properties and methods belong to the class itself, not to its instances. However, many developers confuse the typing of an instance (through this or constructor) with the typing of the class itself as an object. This sometimes leads to errors when accessing static fields within methods or when inheritance occurs.
Solution:
In TypeScript, static members of classes are typed separately from instance members:
Code example:
class User { static count: number = 0; name: string; constructor(name: string) { this.name = name; User.count++; } static getCount(): number { return User.count; } } function createUserClass(): typeof User { return User; }
Key features:
Can static methods work with instance properties of the class directly?
No, static methods do not have access to instance properties via this, as this points to the class itself (the constructor). To work with instance properties, one must work with object instances.
class Demo { static demoStatic() { // this.value; // Error — value is not static } }
Can a static property be accessed through an instance of the class?
No, access to static properties is only possible through the class name itself, not through an instance:
const u = new User('Max'); console.log(u.count); // Error console.log(User.count); // OK
Can static methods be inherited and overridden when inheriting a class?
Yes, static methods can be inherited and overridden, and it will work as expected:
class Animal { static who() { return 'Animal'; } } class Dog extends Animal { static who() { return 'Dog'; } } console.log(Dog.who()); // 'Dog'
A developer stores a counter of created instances as a regular instance property instead of as static. With each object creation, the field increases, but it is not synchronized across all class objects.
Pros:
Cons:
Using static count to account for all objects, correctly increasing it in the constructor and a static method for retrieving the counter.
Pros:
Cons: