- 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
extendskeyword. - This creates a new interface that inherits the properties and methods of the existing interface.
- You can extend an interface using the
- 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:
AnimalInterface:- Defines the basic properties and methods that all animals should have.
DogInterface:- Extends the
Animalinterface usingextends. - Inherits the
nameandeat()properties fromAnimal. - Adds its own specific properties and methods:
breedandbark().
- Extends the
myDogObject:- Implements the
Doginterface, ensuring it has all the required properties and methods.
- Implements the
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.