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:


  • 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.


  • 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:





Class inheritance

Interface implementation




Inherited members

Public and protected

None (must implement all)

Code reuse

Inherits behavior

Enforces contract, allows different implementations



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

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

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

// Class implements Swimmer, "can-do" swimming
class Fish implements Swimmer {
  swim(): void {
    console.log(`${} 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.