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

May 1, 2022 - 2 min read

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

TL;DR

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

  // a protected static field
  protected static className = "Person";

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

// the `className` static field
// cannot be accessed from outside the class
console.log(Person.className); // This is not allowed now ❌

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

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

  // static field
  static className = "Person";

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

// the `className` static field
// can be accessed from outside the class
console.log(Person.className); // This is allowed now

Currently, in the above class, the className static field 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 field like this,

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

  // a protected static field
  protected static className = "Person";

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

// the `className` static field
// cannot be accessed from outside the class
console.log(Person.className); // This is not allowed now ❌

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

We have successfully made the static field 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 😃.