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

Published May 3, 2022

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

TL;DR

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

  // a private static method
  private 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, we need to add the private keyword before the static method like this,

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

  // a private static method
  private 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 private static method called sayHi from outside the class, the TypeScript compiler is showing an error saying Property 'sayHi' is private and only accessible within class 'Person'., 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 😃.


Share on: Facebook Twitter