Introduction
Typescript is a strongly typed, object-oriented, compiled language. It is also a set of tools and typed superset of javascript that means it is Javascript with additional functions and features. And these blogs deal with static methods and properties in typescript. The class that contains static members can be accessed without creating an object by using the class name and dot notation.
For example -
<ClassName>.<StaticMember>
we use the keyword static for defining a static member in the class.
Example -
class Square {
static side: number = 4;
}
In this example, class Square contains a static member side, which will be accessed by Square.side.
Following javascript code will be generated by the typescript for the above mentioned class -
var Square = /** @class */ (function () {
function Square() {
}
Square.side = 4;
return Square;
}());
Static methods
The method that can be shared across class instances is called the static method. We use the static keyword for declaring the static method before the method name.
class Employee {
private static headcount: number = 0;
constructor(
private Name: string,
private lastName: string,
private jobTitle: string) {
Employee.headcount++;
}
public static getHeadcount() {
return Employee.headcount;
}
}
In this example, the access modifier of the declared static property headcount is changed from public to private. The headcount value doesn't change outside the class without creating a new employee object.
Furthermore, static method getHeadcount() is added inside the class, which returns the value of the headcount static property.
we use className.staticMethod() syntax to call the static method.
let mahinder = new Employee('Mahinder', 'singh', 'Front-end Developer');
let jugnu = new Employee('Jugnu', 'kaur', 'Back-end Developer');
let ram = new Employee('ram', 'kapoor', 'Back-end Developer');
console.log(Employee.getHeadcount)); // 3
Output-