In TypeScript, a static property is a property that belongs to a class rather than an instance of the class. It means you can access the static property directly from the class itself, rather than from an instance of the class.
To create and use a static property in TypeScript, you can follow these steps:
1. Define a class.
2. Declare a static property using the ‘static‘ keyword.
3. Assign a value to the static property, if you want to initialize it.
4. Access the static property using the syntax ‘<class-name> .<property-name>‘.
Here’s an example of how to create and use a static property in TypeScript:
class MyClass {
// Declare and initialize a static property
static myStaticProperty: number = 42;
// Regular (non-static) property for comparison
myInstanceProperty: number;
constructor(myInstanceProperty: number) {
this.myInstanceProperty = myInstanceProperty;
}
}
// Access the static property using the class name
console.log(MyClass.myStaticProperty); // Output: 42
// Access an instance property for comparison
const instance = new MyClass(24);
console.log(instance.myInstanceProperty); // Output: 24
The syntax for declaring and accessing a static property is as follows:
Declare a static property: static <property-name> : <property-type>;
Access a static property: <class-name>.<property-name>