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

April 30, 2022 - 2 min read

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

TL;DR

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

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

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

  // a private static field
  private 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 private static field called className from outside the class, the TypeScript compiler is showing an error saying Property 'className' is private and only accessible within class 'Person', which is what we want to happen.

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

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.