ProgrammingFullstack Developer

How does type extension (extends) work, what nuances are there in using types and interfaces, and how does it affect the structure of your project?

Pass interviews with Hintsage AI assistant

Answer

In TypeScript, types can be extended (inherited) using both interface extends and type & type (intersection types). Interfaces can also extend types, and vice versa.

Interfaces use the keyword extends to inherit properties:

interface Animal { name: string; } interface Bird extends Animal { wings: number; }

Types can be combined using &:

type Animal = { name: string }; type Bird = Animal & { wings: number };

Also, an interface can extend another type:

type Base = { id: number }; interface Derived extends Base { description: string; }

Features:

  • Interfaces support declaration merging, while types do not.
  • Interfaces are recommended if other entities are expected to be extended (e.g., for libraries).
  • Nested extends can lead to a complex hierarchy, complicate maintenance, and create naming conflicts.

Trick Question

Can a type (type) be extended through an interface or vice versa? What mistake do most people make?

Many believe that only interfaces can extend interfaces, but in fact, an interface can extend a type:

type Basic = { flag: boolean }; interface Extra extends Basic { name: string; }

However, a type cannot extend other types through extends—only through intersection types (&).

Examples of Real Errors Due to Ignoring the Nuances of the Topic


Story

In one large project, interfaces were merged through extends, forgetting that properties with the same names must match in type. When someone changed a property type in the parent interface, silent conflicts arose in the child interfaces, causing the database to stop aligning with the API.

Story

In a library, type aliases were created with overlapping properties through & (intersections), but some properties were made incompatible in type. TypeScript accepted this at compile-time, but at runtime, the systems had undefined fields.

Story

The team believed that an interface could not be extended by a type, and to extend common functionality, they rewrote all structures from type to interface, wasting a lot of time and effort—when it was simply possible to extend existing types in a non-standard way.