DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Understanding the Difference Between Interface and Type in TypeScript: When to Use Each

When working with TypeScript, developers often encounter two ways to define shapes for objects: interface and type. While they can look similar, there are important differences and best-use cases.

Key Differences

  • Extensibility:

    • interface can be extended multiple times by declaration merging or by using the extends keyword.
    • type is closed after its definition. You can't merge or reopen a type, but you can create new types by intersecting them.
  • Declaration:

    • Use interface for defining the shape of objects, especially when you expect the structure to grow.
    • Use type for composing types, unions, primitives, and tuples.
  • Implements:

    • Classes can implement both interfaces and types, but interfaces work more naturally with class implementation.
  • Union and Intersection:

    • Only type can create union types (type AorB = A | B) and intersection types (type AB = A & B).

Examples

Interface Example

interface User {
  name: string;
  age: number;
}

interface User {
  email: string;
}

// Merged into:
// { name: string; age: number; email: string }
Enter fullscreen mode Exit fullscreen mode

Type Example

type User = {
  name: string;
  age: number;
};
// type User = { email: string } // Error: Cannot redeclare 'User'

type StringOrNumber = string | number;
Enter fullscreen mode Exit fullscreen mode

When to Use Each

  • Use interface when:

    • You want to model the shape of objects and classes
    • You expect extensions (from libraries or other code)
    • Declaration merging is desirable
  • Use type when:

    • You need to use unions or intersections
    • You want to alias primitives or tuples (e.g., type Name = string or type Point = [number, number])
    • Complex type composition is required

Summary Table

Feature interface type
Extensible/mergeable Yes No
Supports unions No Yes
Suitable for objects Yes Yes
Use with primitives No Yes
Best for classes Yes Yes (but interface best)

In practice: Use interface for data shapes and type for type transformations and combinations.

Top comments (0)