0
0
Typescriptprogramming~3 mins

Why Extending interfaces in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix one place and update all related types instantly?

The Scenario

Imagine you have several objects representing different types of vehicles, each with some shared properties like make and model, but also some unique ones. You try to write separate type definitions for each, repeating the shared parts over and over.

The Problem

This manual repetition is slow and error-prone. If you want to update the shared properties, you must change every type separately. It's easy to forget one, causing bugs and inconsistent code.

The Solution

Extending interfaces lets you create a base interface with shared properties, then build new interfaces that add or change details. This keeps your code clean, consistent, and easy to update.

Before vs After
Before
interface Car { make: string; model: string; doors: number; }
interface Truck { make: string; model: string; capacity: number; }
After
interface Vehicle { make: string; model: string; }
interface Car extends Vehicle { doors: number; }
interface Truck extends Vehicle { capacity: number; }
What It Enables

You can build complex, organized type structures that grow with your app without repeating yourself or risking mistakes.

Real Life Example

Think of a delivery app where you track cars, trucks, and bikes. Each vehicle shares some info, but also has unique details. Extending interfaces helps you model this clearly and safely.

Key Takeaways

Extending interfaces avoids repeating shared properties.

It makes updating types easier and safer.

It helps organize related data clearly in your code.