We make use of the keyword static
to declare static methods and static properties in Typescript. In this article, we will look at how to declare and use them in TypeScript.
Static Methods
To declare a static method we need to prefix the method with static
keyword. Let us first create a regular method and access it.
class Student {
greet() {
console.log("Hello there!");
}
}
let student = new Student();
student.greet(); // Hello there!
To access the greet()
method, we first need to create an instance of class Student and then call the method like student.greet()
where student
is an object of class Student
.
Now we will convert the regular method to a static method by prefixing static
.
class Student {
static greet() {
console.log("Hello there!");
}
}
Student.greet(); // Hello there!
As you can see from the above declaration, method greet()
can be accessed without creating an object.
Static Properties
Static properties can also be declared using the static
keyword.
class Student {
static university = "Bob's University";
}
console.log(Student.university); // Bob's University
However, it is important to note that static properties cannot be accessed from within the class methods.
class Student {
static university = "Bob's University";
greet() {
console.log(this.university);
}
}
This will throw an error - Property 'university' does not exist on type 'Student'. Did you mean to access the static member 'Student.university' instead?
If you want to access them inside methods you can call the property like below:
class Student {
static university = "Bob's University";
greet() {
console.log(Student.university);
}
}
let student = new Student();
student.greet(); // Bob's University