add a protected static property to a class in typescript

To add a protected static property to a class in TypeScript, you can use the protected keyword to make the property accessible within the class and any derived classes, and the static keyword to make the property shared by all instances of the class.

Here's an example:

index.ts
class MyClass {
  protected static myProperty: string = "hello";
}

console.log(MyClass.myProperty); // "hello"

class MyDerivedClass extends MyClass {
  public getMyProperty(): string {
    return MyDerivedClass.myProperty;
  }
}

console.log(MyDerivedClass.myProperty); // "hello"
const instance = new MyDerivedClass();
console.log(instance.myProperty); // Error: Property 'myProperty' is protected and only accessible within class 'MyClass' and its subclasses.
console.log(instance.getMyProperty()); // "hello"
514 chars
17 lines

In this example, we declare a MyClass class with a protected static property myProperty that is initialized to the string "hello". We can access this property directly on the class itself (MyClass.myProperty) or on a derived class (MyDerivedClass.myProperty) because it's static.

However, we cannot access the property on an instance of the class (instance.myProperty) because it's protected. Instead, we create a getter method getMyProperty() in the MyDerivedClass class to access the property from within the class hierarchy.

gistlibby LogSnag