Typescript type vs interface

Manthan Ankolekar - Nov 29 '23 - - Dev Community

In TypeScript, both type and interface are used to define shapes of objects or types. They seem similar in functionality, but they have some differences in how they can be used and extended.

Interfaces:

Interfaces are used to define the structure or shape of an object. They can describe the contract that other classes or objects must adhere to. They are also capable of being extended or merged.

// Interface example
interface Person {
  name: string;
  age: number;
}

// Implementing the interface
const person: Person = {
  name: 'Alice',
  age: 30,
};
Enter fullscreen mode Exit fullscreen mode

Types:

Types are used to create aliases for different types in TypeScript. They allow you to create a name for any valid type, including built-in types, union types, intersection types, and more. Types are flexible and can represent complex types using intersections, unions, and conditional types.

// Type example
type Point = {
  x: number;
  y: number;
};

// Using the type alias
const point: Point = {
  x: 10,
  y: 20,
};
Enter fullscreen mode Exit fullscreen mode

Differences:

Extending/merging:

  • Interfaces support declaration merging. If you declare two interfaces with the same name, TypeScript merges them into one.
  • Types can be used in combination through intersection (&) or union (|) but cannot be extended or merged in the same way as interfaces.

Syntax:

  • Interfaces use the interface keyword.
  • Types use the type keyword.

Declaration:

  • Interfaces are more suitable for defining object shapes, contracts, or classes that implement them.
  • Types are more versatile and can define not only object shapes but also union types, intersection types, conditional types, and more.

When to use which:

Use interface when:

  • Defining contracts for objects, classes, or their shapes.
  • Needing declaration merging or extending existing types/contracts.

Use type when:

  • Creating a union, intersection, or any other complex type.
  • Defining aliases for primitive types, unions, intersections, or complex types to improve code readability.

In many cases, both interfaces and types can accomplish the same tasks, and choosing between them often comes down to personal preference or specific needs within a codebase. There are no strict rules dictating when to use one over the other.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .