TypeScript
/Intermediate
Extending Interfaces
Definition
The `extends` keyword allows one interface to inherit all the properties of another interface, promoting reusability and DRY (Don't Repeat Yourself) code.
Explain Like I'm New
Imagine you have a basic 'Vehicle' blueprint (has wheels, has color). You want to build a 'Car' blueprint. Instead of rewriting 'wheels' and 'color', you tell the Car blueprint to 'extend' the Vehicle blueprint, automatically copying its requirements, and then you just add 'doors'.
Real World Example
A base `APIResponse` interface with `{ status: number, message: string }`, extended by a `UserResponse` interface that adds `{ data: User }`.
Common Use Cases
- •Component props inheritance in React
- •Building complex hierarchical data models
Interactive Example
// Base Interface interface Animal { name: string; age: number; } // Inherits 'name' and 'age', adds 'breed' interface Dog extends Animal { breed: string; } const myDog: Dog = { name: "Rex", age: 3, breed: "German Shepherd" }; // Extending Multiple Interfaces interface CanSwim { swimSpeed: number; } interface CanFly { flySpeed: number; } interface Duck extends CanSwim, CanFly { quackVolume: number; }
Interview Questions
basic
- What keyword is used to inherit from an interface?
intermediate
- Can an interface extend multiple interfaces at once?
advanced
- What happens if you extend an interface and redefine a property with a different type?