Table of contents

  1. 1. Tutorial
  2. 2. Identifying static methods
  3. 3. Code samples
    1. 3.1. Instance method
    2. 3.2. Static method

When developing class functions that don’t rely on an internal state, it’s a good idea to turn them into static methods. This can be easily done by adding the keyword static to your function’s declaration.

Tutorial

Static methods are a great concept to share functionality from a class without instantiating the class. In the following live session Benny will show you how to implement a static method. As a bonus you will also learn how to share type definitions with TypeScript to extend the reusability of your own code:

Identifying static methods

When checking a function’s implementation you can easily recognize whether a function should be converted into a static method. If your function doesn’t use the this keyword or any other class member, then it can be easily converted to a static function. To create a static function simply add the static keyword and call it directly from the class instead of calling it from the instance of the class.

Code samples

Instance method

1
2
3
4
5
6
7
8
export class MyClass {
myFunction(text: string) {
return text;
}
}

const instance = new MyClass();
instance.myFunction('My Text');

Static method

1
2
3
4
5
6
7
export class MyClass {
static myFunction(text: string) {
return text;
}
}

MyClass.myFunction('My Text');