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

To call a public static property on an instance of a class in TypeScript, you need to access the property through the class name, not the instance. Here's an example:

index.ts
class MyClass {
  public static myProperty: string = 'Hello World';
}

const myInstance = new MyClass();

// accessing static property through class name
console.log(MyClass.myProperty);

// static properties can also be accessed through instance, but TypeScript will give a warning:
console.log(myInstance.constructor.myProperty);
332 chars
12 lines

In the code above, we define a class MyClass with a public static property myProperty set to the string 'Hello World'. Then, we create an instance of the class and attempt to access the property first through the class name, and then through the instance.

Note that while it is possible to access static properties through an instance of a class in TypeScript, doing so will generate a warning. It is recommended to access static properties through the class name for clarity and consistency.

gistlibby LogSnag