add a public static property to a class in typescript

To add a public static property to a class in TypeScript, you can declare it inside the class declaration using the static keyword.

Example:

index.ts
class MyClass {
  public static myStaticProperty: string = "Hello World!";
}

console.log(MyClass.myStaticProperty); // Output: "Hello World!"
143 chars
6 lines

In this example, we declared a public static property called myStaticProperty on the MyClass class. This property can be accessed without needing an instance of the class.

We can also modify the value of this property:

index.ts
MyClass.myStaticProperty = "Goodbye World!";

console.log(MyClass.myStaticProperty); // Output: "Goodbye World!"
113 chars
4 lines

This code will change the value of the myStaticProperty property to "Goodbye World!" and then log it to the console.

Static properties are useful for declaring values that are associated with a class as a whole, rather than with individual instances of the class.

gistlibby LogSnag