ProgrammingFullstack Developer

Tell us about interfaces and type aliases in TypeScript. How do they differ and in what cases should one approach be chosen over the other?

Pass interviews with Hintsage AI assistant

Answer.

Both mechanisms — interface and type alias — allow you to describe data structures (objects, functions, complex types).

  • Interface — classic interface declaration. Allows for extending interfaces, merging (declaration merging), and is easy to inherit.
  • Type alias — creates a new type alias. Can be combined using union / intersection, and assigned to any entity: primitives, functions, tuples, etc.

Differences:

  • Extensibility: interface is better for object structures, supports declarative merging.
  • Flexibility: type alias is versatile, suitable for everything: union (|) and intersection (&).

Example:

interface Animal { name: string } interface Dog extends Animal { bark(): void } // type alias for combining types: type MyType = string | number type Cat = Animal & { purr(): void }

Recommended:

  • For public APIs — use interface.
  • For complex unions and aliases — use type.

Trick question.

Question: Can a new field be added to a type defined via type alias in another file?

Answer:

No. Type alias cannot be declaratively extended from another file, unlike interface.

Example:

// main.ts type User = { name: string } // another.ts type User = { age: number } // Error: Duplicate identifier // interface: // main.ts interface User { name: string } // another.ts interface User { age: number } // Ok, User = { name: string, age: number }

Examples of real errors due to misunderstandings about the topic.


Story

In a large project, common data structures were defined via type alias. When it became necessary to add a field to an existing type from another package, it turned out that type alias does not support declaration merging — had to rewrite to interface, causing delays.


Story

One of the developers described functions via interface, and then tried to add a Union type (a string or a function) — it turned out that interface is not suitable for this, and all definitions had to be changed to type alias with intersection/union.


Story

After changing the type from interface to type alias, they confused the extension syntax: tried to use extends, instead of combining via &. The error manifested late and the reason was not immediately understood.