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:
-
Class
Point
:- This class defines two properties:
x
andy
. - A constructor is used to initialize these properties when an object of
Point
is created.
- This class defines two properties:
-
Interface
Point3d
:- The interface
Point3d
extends from the classPoint
, meaning it must include all properties ofPoint
(i.e.,x
andy
). - It also includes an additional property
z
, making it a 3D point.
- The interface
-
Object
point3d
:- The object
point3d
is created with propertiesx
,y
, andz
, satisfying the structure ofPoint3d
, which extendsPoint
.
- The object
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.