Translate

Saturday 17 February 2024

What's the difference between extends and implements in TypeScript?73

 What's the difference between extends and implements in TypeScript?


Both extends and implements keywords in TypeScript deal with relationships between classes and interfaces, but they serve different purposes:

extends:

  • Used for class inheritance.

  • Allows a class to inherit properties and methods from another class (base class).

  • Establishes an "is-a" relationship, meaning the subclass is a type of the base class.

  • The subclass inherits all public and protected members of the base class, unless explicitly overridden.

  • Offers code reuse and organization for related classes.

implements:

  • Used for interface implementation.

  • Allows a class to declare that it conforms to the structure defined by an interface.

  • Establishes a "can-do" relationship, meaning the class can perform the actions specified in the interface.

  • The class must provide implementations for all methods declared in the interface.

  • Promotes abstraction and loose coupling, decoupling implementation from usage.

Key Differences:





Feature

extends

implements

Purpose

Class inheritance

Interface implementation

Relationship

"is-a"

"can-do"

Inherited members

Public and protected

None (must implement all)

Code reuse

Inherits behavior

Enforces contract, allows different implementations

Example:


TypeScript

// Base class with properties and methods
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  move(): void {
    console.log(`${this.name} is moving.`);
  }
}

// Subclass inherits from Animal, "is-a" Animal
class Dog extends Animal {
  bark(): void {
    console.log(`${this.name} barks!`);
  }
}

// Interface defines expected behavior
interface Swimmer {
  swim(): void;
}

// Class implements Swimmer, "can-do" swimming
class Fish implements Swimmer {
  swim(): void {
    console.log(`${this.name} is swimming!`);
  }
}

Choosing between extends and implements:

  • Use extends when you want to create a class hierarchy with shared properties and behaviors.

  • Use implements when you want to enforce a specific contract on a class without requiring inheritance.

  • You can also use both within the same class when it inherits from a base class and implements one or more interfaces.

By understanding the distinction between extends and implements, you can effectively utilize them in your TypeScript code to achieve code reuse, maintainability, and flexibility, while fostering clear and well-structured object-oriented design.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.