How to make a static method accessible only in its class and subclasses in TypeScript?

May 2, 2022 - 2 min read

To make a static method accessible only in its class and subclasses, you need to make the static method into a protected static method using the protected keyword before the static method in TypeScript.

TL;DR

// a simple class
class Person {
  name: string;
  age: number;

  // a protected static method
  protected static sayHi() {
    console.log("Hi, Person!");
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// the `sayHi` static method
// cannot be accessed from outside the class
Person.sayHi(); // This is not allowed now ❌

For example, let's say we have a class called Person with 2 fields, a constructor, and a static method like this,

// a simple class
class Person {
  name: string;
  age: number;

  // static method
  static sayHi() {
    console.log("Hi, Person!");
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// the `sayHi` static method
// can be accessed from outside the class
Person.sayHi(); // This is allowed now

Currently, in the above class, the sayHi static method is public and can be accessed from outside the class.

To make it only accessible within the Person class and any other classes that extend the Person class (subclasses), we need to add the protected keyword before the static method like this,

// a simple class
class Person {
  name: string;
  age: number;

  // a protected static method
  protected static sayHi() {
    console.log("Hi, Person!");
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// the `sayHi` static method
// cannot be accessed from outside the class
Person.sayHi(); // This is not allowed now ❌

As you can see from the above code that when we try to access the protected static method called sayHi from outside the class, the TypeScript compiler is showing an error saying Property 'sayHi' is protected and only accessible within class 'Person' and its subclasses., which is what we want to happen.

We have successfully made the static method to be accessible within its class and subclasses only in TypeScript. Yay 🥳!

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.