Open In App

How to Define Static Property in TypeScript Interface ?

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A static property in a class is a property that belongs to the class itself, rather than to instances of the class. It is shared among all instances of the class and can be accessed without creating an instance of the class. Static properties are defined using the static keyword in front of the property.

In TypeScript, you can’t directly define static properties in an interface because interfaces are used to define the shape of instance members of a class or object. Since static properties belong to the class itself and not to instances, they are not part of the shape defined by an interface.

Solution for Defining Static Properties TypeScript interface:

To work around this limitation, you can use a combination of a class and an interface. The class will implement the interface, and you can include the static property directly in the class.

Example: In this example, the static property staticProperty is directly defined within the MyClass class, and the class implements the MyInterface interface for instance-level properties. This approach provides a clear separation between instance and static properties.

Javascript




// Define an interface without static properties
interface MyInterface {
    instanceProperty: string;
    // ... other instance properties
}
 
class MyClass implements MyInterface {
    static staticProperty: string = "Static Value";
    instanceProperty: string;
 
    constructor(instanceProperty: string) {
        this.instanceProperty = instanceProperty;
    }
}
 
// Accessing static property
// "Static Value"
console.log(MyClass.staticProperty);
 
// Creating an instance of the class
const myInstance = new MyClass("Instance Value");
 
// "Instance Value"
console.log(myInstance.instanceProperty);


Output:

Static Value
Instance Value

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads