In TypeScript, interfaces are often used to define the structure of an object. Interestingly, classes can also be used to define the shape or structure of an object, which can be used in place of an interface. This concept is called “Using a class as an interface”.

Example: Using a Class as an Interface

// Define a class with properties
class Point {
  x: number;
  y: number;
 
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}
 
// Extend the class with an interface to add another property
interface Point3d extends Point {
  z: number;
}
 
// Creating an object with the structure of Point3d
let point3d: Point3d = { x: 1, y: 2, z: 3 };
 
console.log(point3d); // Output: { x: 1, y: 2, z: 3 }

Key Points:

  1. Class Point:

    • This class defines two properties: x and y.
    • A constructor is used to initialize these properties when an object of Point is created.
  2. Interface Point3d:

    • The interface Point3d extends from the class Point, meaning it must include all properties of Point (i.e., x and y).
    • It also includes an additional property z, making it a 3D point.
  3. Object point3d:

    • The object point3d is created with properties x, y, and z, satisfying the structure of Point3d, which extends Point.

This approach can be useful when you want to enforce the structure of objects while leveraging the benefits of class implementation (e.g., methods) in conjunction with interfaces.