0
0
Typescriptprogramming~5 mins

Implementing interfaces in classes in Typescript

Choose your learning style9 modes available
Introduction

Interfaces help us define a clear shape for objects. Classes can use interfaces to promise they will have certain properties and methods.

When you want to make sure a class has specific properties and methods.
When you want to share a common structure between different classes.
When you want to write code that works with any class that follows the same interface.
When you want to catch mistakes early by checking if a class follows the rules.
When you want to improve code readability by clearly showing what a class should do.
Syntax
Typescript
interface InterfaceName {
  propertyName: type;
  methodName(param: type): returnType;
}

class ClassName implements InterfaceName {
  propertyName: type;
  constructor(...) { ... }
  methodName(param: type): returnType {
    // method body
  }
}

The implements keyword is used to make a class follow an interface.

All properties and methods from the interface must be in the class.

Examples
This example shows a class Dog that promises to have a name and a makeSound method as defined in the Animal interface.
Typescript
interface Animal {
  name: string;
  makeSound(): void;
}

class Dog implements Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  makeSound() {
    console.log('Woof!');
  }
}
Here, Car implements Vehicle interface, so it must have speed and move method.
Typescript
interface Vehicle {
  speed: number;
  move(distance: number): void;
}

class Car implements Vehicle {
  speed: number;
  constructor(speed: number) {
    this.speed = speed;
  }
  move(distance: number) {
    console.log(`Car moved ${distance} meters at speed ${this.speed}`);
  }
}
Sample Program

This program defines a Person interface and a Student class that implements it. The Student class has the required properties and method. When we create a Student and call greet, it prints a greeting message.

Typescript
interface Person {
  firstName: string;
  lastName: string;
  greet(): void;
}

class Student implements Person {
  firstName: string;
  lastName: string;

  constructor(firstName: string, lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  greet() {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);
  }
}

const student = new Student('Alice', 'Johnson');
student.greet();
OutputSuccess
Important Notes

If a class misses any property or method from the interface, TypeScript will show an error.

Interfaces only exist during development for checking types; they do not create code in JavaScript.

You can implement multiple interfaces by separating them with commas.

Summary

Interfaces define what properties and methods a class must have.

Use implements keyword in a class to follow an interface.

This helps catch errors early and makes code easier to understand.