Static Methods & Properties in TypeScript (Live Playground)
In this tutorial, we will explore static methods and properties in TypeScript, which are essential for creating class-level functionality in advanced object-oriented programming (OOP).
Static Properties
Static properties belong to the class itself rather than to an instance of the class. They can be accessed using the class name, without creating an instance of the class.
class Circle {
static PI = 3.14;
constructor(public radius: number) {}
area(): number {
return Circle.PI * this.radius * this.radius;
}
}
console.log(Circle.PI); // 3.14
const circle = new Circle(5);
console.log(circle.area()); // 78.5
Static Methods
Static methods are similar to static properties but represent functions that belong to the class. They can be called using the class name and cannot access non-static members of the class.
class Circle {
static PI = 3.14;
constructor(public radius: number) {}
area(): number {
return Circle.PI * this.radius * this.radius;
}
static circumference(radius: number): number {
return 2 * Circle.PI * radius;
}
}
console.log(Circle.PI); // 3.14
console.log(Circle.circumference(5)); // 31.4
const circle = new Circle(5);
console.log(circle.area()); // 78.5
Using Static Members in Subclasses
Static members can also be accessed and overridden in subclasses, allowing for more flexibility and code reusability in your applications.
class Shape {
static description = 'A generic shape';
static getDescription(): string {
return this.description;
}
}
class Circle extends Shape {
static description = 'A circle shape';
constructor(public radius: number) {
super();
}
}
console.log(Shape.getDescription()); // A generic shape
console.log(Circle.getDescription()); // A circle shape
Conclusion
In this tutorial, we have explored static methods and properties in TypeScript, which are essential for creating class-level functionality in advanced object-oriented programming (OOP). As you continue learning TypeScript, make sure to practice using static methods, properties, and other OOP techniques to create more flexible, reusable, and maintainable code in your applications.