TypeScript Static Methods Tutorial

In this TypeScript tutorial we learn about static methods that belong to a class, instead of an instance of a class.

We cover the 'static' keyword, how to define and invoke them as well as what happens when static methods have the same name.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a static class method

A static class method is a method that belongs to the class itself, not the instance of a class.

That means we don’t need an object to call a static class method. We call them directly from the class itself.

Note: We should compile the following scripts with the compiler flag –target es6 or greater.

How to define a static class method

To define a static class method, we replace the function keyword with the static keyword in front of a method definition in a class.

Syntax:
static method_name() {

  // body
}
Example:
class Person {

  static walk() {
    console.log("Walking...");
  }
}

How to call a static class method

As we’ve mentioned before, a static method doesn’t need an object in order for us to use it, it can be called directly from the class.

Example:
class Person {

  static walk() {
    console.log("Walking...");
  }
}

// invoke method directly
// from the 'Person' class
Person.walk();

In the example above, we call the method without creating an object. When we run the example, the text is printed to the console.

Static class methods with duplicate names

In Javascript, we may have as many static class methods as we need, even ones with similar names.

If we do have static methods with similar names, the compiler will always invoke the last one.

Example:
<script>

  class Person {

    static walk() {
      document.write("Walking first...");
    }

    static walk() {
      document.write("Walking last...");
    }
  }

  Person.walk();

</script>

In the Javascript example above, the translator will run the second walk() method.

But, in TypeScript this isn’t allowed, the compiler will raise an error.

Output:
main.ts:3:10 - error TS2393: Duplicate function implementation.

3   static walk() {
           ~~~~

main.ts:7:10 - error TS2393: Duplicate function implementation.

7   static walk() {
           ~~~~

Summary: Points to remember

  • A static class method belongs to a class, not an instance.
  • We call a static method directly from the class, using the class name. We don’t need to create an object instance.
  • A static method uses the static keyword instead of the function keyword when we define it.
  • If more than one static method share the same name, the compiler will raise an error.