Web Analytics

Extending Interfaces

Beginner~15 min

Interfaces can extend other interfaces to build complex types through inheritance, promoting code reuse and maintainability.

Extending Interfaces

Use the extends keyword to inherit properties from parent interfaces:

Output
Click Run to execute your code
How It Works: The child interface inherits ALL properties from the parent, plus adds its own.

Multiple Inheritance

TypeScript interfaces can extend multiple interfaces at once:

interface Timestamped {
    createdAt: Date;
    updatedAt: Date;
}

interface Named {
    firstName: string;
    lastName: string;
}

// Extends both interfaces
interface User extends Named, Timestamped {
    email: string;
}

let user: User = {
    firstName: "Alice",
    lastName: "Johnson",
    email: "[email protected]",
    createdAt: new Date(),
    updatedAt: new Date()
};

When to Extend Interfaces

  • Shared properties: Multiple types need common fields
  • Hierarchies: Base type with specialized variants
  • Composition: Combine multiple concerns
  • API responses: Base response + specific data

Interface Extension Patterns

Pattern Use Case Example
Single Inheritance Simple hierarchy Dog extends Animal
Multiple Inheritance Combine traits User extends Named, Timestamped
Chain Extension Deep hierarchy Admin extends User extends Person

Common Mistakes

1. Conflicting Property Types

interface A {
    value: string;
}

interface B {
    value: number;
}

// โœ— Wrong - conflicting types for 'value'
interface C extends A, B { }  // Error!

// โœ“ Correct - compatible types
interface A {
    value: string | number;
}

interface B {
    value: number;
}

interface C extends A, B { }  // OK

2. Forgetting Parent Properties

interface Animal {
    nameAnimal: string;
}

interface Dog extends Animal {
    breed: string;
}

// โœ— Wrong - missing 'nameAnimal'
let dog: Dog = {
    breed: "Labrador"
};

// โœ“ Correct
let dog: Dog = {
    nameAnimal: "Buddy",
    breed: "Labrador"
};
Best Practice: Keep interface hierarchies shallow (2-3 levels max) for maintainability.

Summary

  • Use extends to inherit properties
  • Can extend multiple interfaces
  • Child inherits ALL parent properties
  • Great for code reuse and composition

What's Next?

Congratulations! You've completed Module 2. Next: Classes & OOP!