Merging classes with interfaces lets you add extra properties or types to a class without changing its original code. It helps keep your code organized and clear.
Merging classes with interfaces in Typescript
class ClassName { // class members } interface ClassName { // additional members }
The interface must have the same name as the class to merge.
TypeScript combines the class and interface members into one type.
age property to the Person class type.class Person { name: string; constructor(name: string) { this.name = name; } } interface Person { age: number; }
year property and a getAge method type to the Car class.class Car { model: string; constructor(model: string) { this.model = model; } } interface Car { year: number; getAge(): number; }
This example shows a class Book merged with an interface that adds author and getSummary. We add the interface members to the class prototype so instances can use them.
class Book { title: string; constructor(title: string) { this.title = title; } } interface Book { author: string; getSummary(): string; } // Implementing the interface members Book.prototype.author = "Unknown"; Book.prototype.getSummary = function() { return `${this.title} by ${this.author}`; }; const myBook = new Book("Learn TypeScript"); myBook.author = "Jane Doe"; console.log(myBook.getSummary());
Merging only affects types, not the actual class implementation unless you add code like in the example.
You can add properties and methods in the interface, but you must implement them in the class or its prototype.
This technique helps when you want to extend types without modifying original class code.
Merging classes with interfaces lets you add extra type info to classes.
The interface must have the same name as the class to merge.
You still need to implement added members in the class or prototype.