Skip to content

Latest commit

 

History

History
89 lines (71 loc) · 2.25 KB

File metadata and controls

89 lines (71 loc) · 2.25 KB

Interfaces:

  • Definition:
    • Interfaces define the structure of an object, specifying the names and types of its properties and methods.
  • Purpose:
    • They enforce type checking and ensure that objects conform to a specific contract.
    • They enhance code readability and maintainability by providing clear type definitions.

Extending Interfaces:

  • Syntax:
    • You can extend an interface using the extends keyword.
    • This creates a new interface that inherits the properties and methods of the existing interface.
  • Example:
interface Animal {
  name: string;
  eat(): void;
}

interface Dog extends Animal {
  breed: string;
  bark(): void;
}

let myDog: Dog = {
  name: "Buddy",
  breed: "Golden Retriever",
  eat() {
    console.log("Dog is eating");
  },
  bark() {
    console.log("Woof!");
  },
};

myDog.eat();
myDog.bark();
console.log(myDog.breed);

Explanation:

  1. Animal Interface:
    • Defines the basic properties and methods that all animals should have.
  2. Dog Interface:
    • Extends the Animal interface using extends.
    • Inherits the name and eat() properties from Animal.
    • Adds its own specific properties and methods: breed and bark().
  3. myDog Object:
    • Implements the Dog interface, ensuring it has all the required properties and methods.

Multiple Interface Extension:

  • TypeScript also supports extending multiple interfaces.
interface Colorful {
  color: string;
}

interface Printable {
  print(): void;
}

interface ColorfulPrintable extends Colorful, Printable {
  // additional properties or methods.
}

let myObject: ColorfulPrintable = {
  color: "red",
  print() {
    console.log("Printing in red");
  },
};

Benefits of Extending Interfaces:

  • Code Reusability:
    • Avoids duplicating code by inheriting common properties and methods.
  • Hierarchical Type Definitions:
    • Allows you to create a hierarchy of related types, making your code more organized.
  • Improved Maintainability:
    • Changes to a base interface automatically propagate to its derived interfaces.
  • Enhanced Type Safety:
    • Ensures that objects conform to the required contracts, reducing the risk of runtime errors.