0
0
Typescriptprogramming~5 mins

Merging classes with interfaces in Typescript

Choose your learning style9 modes available
Introduction

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.

When you want to add new properties or methods to a class from outside its original definition.
When you want to describe extra types or shapes that a class should have.
When working with third-party classes and you want to extend their types safely.
When you want to combine class behavior with additional type information.
When you want to keep your code modular and easy to maintain.
Syntax
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.

Examples
This adds an age property to the Person class type.
Typescript
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

interface Person {
  age: number;
}
This adds a year property and a getAge method type to the Car class.
Typescript
class Car {
  model: string;
  constructor(model: string) {
    this.model = model;
  }
}

interface Car {
  year: number;
  getAge(): number;
}
Sample Program

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.

Typescript
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());
OutputSuccess
Important Notes

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.

Summary

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.