call a private static property on an instance of a class in typescript

In TypeScript, private properties cannot be accessed outside of their defining class. And static properties belong to the class itself, not to its instances.

So, to call a private static property on an instance of a class in TypeScript, you need to do the following:

index.ts
class MyClass {
  private static myPrivateStaticProp: string = 'Hello, world!';

  someMethod() {
    console.log(MyClass.myPrivateStaticProp);
  }
}

const myObj = new MyClass();
myObj.someMethod(); // Output: "Hello, world!"
227 chars
11 lines

This syntax accesses the private static property myPrivateStaticProp of the class MyClass by using MyClass.myPrivateStaticProp in the someMethod method. The myObj instance of MyClass can call someMethod and access the private static property because it belongs to the class, not the instance.

Note: If the static property were public, you could access it directly as MyClass.myPublicStaticProp.

gistlibby LogSnag