When to use static methods in TypeScript?
Static methods in programming are functions that can be called directly from a class without needing to create an instance of the class. They are useful when you have a function that doesn't rely on any internal state of the class.
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.
Contents
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.