0
0
Typescriptprogramming~5 mins

Class implementing multiple interfaces in Typescript

Choose your learning style9 modes available
Introduction

Using multiple interfaces lets a class promise to do many different jobs. This helps organize code and makes it clear what the class can do.

When a class needs to follow rules from more than one source.
When you want to combine different abilities into one class.
When you want to make sure a class has certain methods from different groups.
When designing flexible and reusable code parts.
When you want to separate what a class does into clear sections.
Syntax
Typescript
interface Interface1 {
  method1(): void;
}

interface Interface2 {
  method2(): void;
}

class MyClass implements Interface1, Interface2 {
  method1(): void {
    // code for method1
  }

  method2(): void {
    // code for method2
  }
}

You list multiple interfaces separated by commas after implements.

The class must provide all methods from all interfaces it implements.

Examples
This class Duck promises to fly and swim by implementing both interfaces.
Typescript
interface Flyer {
  fly(): void;
}

interface Swimmer {
  swim(): void;
}

class Duck implements Flyer, Swimmer {
  fly(): void {
    console.log("Duck is flying");
  }
  swim(): void {
    console.log("Duck is swimming");
  }
}
The Book class can both read and write text by following two interfaces.
Typescript
interface Reader {
  read(): string;
}

interface Writer {
  write(text: string): void;
}

class Book implements Reader, Writer {
  private content = "";
  read(): string {
    return this.content;
  }
  write(text: string): void {
    this.content += text;
  }
}
Sample Program

This program shows a class ConsoleLogger that can both log messages and handle errors by implementing two interfaces.

Typescript
interface Logger {
  log(message: string): void;
}

interface ErrorHandler {
  handleError(error: string): void;
}

class ConsoleLogger implements Logger, ErrorHandler {
  log(message: string): void {
    console.log(`Log: ${message}`);
  }

  handleError(error: string): void {
    console.error(`Error: ${error}`);
  }
}

const logger = new ConsoleLogger();
logger.log("Application started");
logger.handleError("File not found");
OutputSuccess
Important Notes

Interfaces only describe what methods a class should have, not how they work.

A class can implement any number of interfaces to combine features.

If you forget to add a method from an interface, TypeScript will show an error.

Summary

Classes can promise to do many things by implementing multiple interfaces.

This helps keep code organized and clear.

Always implement all methods from every interface you list.