In TypeScript, the static
keyword is used to define properties or methods that belong to the class itself rather than to instances of the class. Here are the key aspects of static
in TypeScript:
-
Static Properties:
- When a property is declared as
static
in a class, it means that the property is associated with the class itself, not with instances of the class. - Static properties are accessed using the class name, not an instance of the class.
- When a property is declared as
class MyClass {
static myStaticProperty: number = 10;
}
console.log(MyClass.myStaticProperty); // Accessing static property
-
Static Methods:
- Similar to static properties, static methods are associated with the class rather than instances.
- They are called on the class itself, not on an instance of the class.
class MathOperations {
static add(x: number, y: number): number {
return x + y;
}
}
console.log(MathOperations.add(5, 3)); // Calling static method
-
Singleton Pattern:
- In TypeScript, the
static
keyword is often used in conjunction with the Singleton pattern. - By declaring a
static
property that holds a single instance of the class, you ensure that only one instance exists throughout the application.
- In TypeScript, the
class Singleton {
private static instance: Singleton;
private constructor() { }
static getInstance(): Singleton {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
const singletonInstance1 = Singleton.getInstance();
const singletonInstance2 = Singleton.getInstance();
console.log(singletonInstance1 === singletonInstance2); // true
-
No Access to Instance Members:
- Inside a
static
method, you cannot directly access instance members (properties or methods) of the class because the method is associated with the class, not a specific instance.
- Inside a
class Example {
static staticMethod() {
// Can't access instance property directly
// console.log(this.instanceProperty); // Error
}
instanceProperty: string = "Hello";
}
In summary, static
in TypeScript is used to define properties and methods that are associated with the class itself, rather than with instances of the class. It is commonly used for utility methods, constants, and for implementing patterns like the Singleton pattern.
Top comments (0)