Interface vs Type in TypeScript

Nadim Chowdhury - Nov 23 '23 - - Dev Community

In TypeScript, both interface and type are used to define shapes or structures for values. They are often used interchangeably, but there are some subtle differences between them.

Interfaces:

  1. Declaration Merging:
    • Interfaces support declaration merging. This means that if you define two interfaces with the same name, TypeScript will merge them into a single interface. This allows you to spread the definition of an interface across multiple files.
   interface Person {
     name: string;
   }

   interface Person {
     age: number;
   }

   const john: Person = {
     name: 'John',
     age: 25,
   };
Enter fullscreen mode Exit fullscreen mode
  1. Extending:
    • Interfaces can extend other interfaces using the extends keyword.
   interface Shape {
     color: string;
   }

   interface Square extends Shape {
     sideLength: number;
   }

   const square: Square = {
     color: 'red',
     sideLength: 5,
   };
Enter fullscreen mode Exit fullscreen mode

Types:

  1. Union and Intersection:
    • Types can be used to create union and intersection types more easily.
   type Status = 'active' | 'inactive';
   type Employee = {
     id: number;
     name: string;
   };

   type EmployeeStatus = Employee & { status: Status };
Enter fullscreen mode Exit fullscreen mode
  1. Mapped Types:
    • Types allow the use of mapped types, which can dynamically create new types based on the properties of an existing type.
   type Partial<T> = {
     [P in keyof T]?: T[P];
   };

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

   type PartialPerson = Partial<Person>;
Enter fullscreen mode Exit fullscreen mode
  1. Tuple Types:
    • Types can represent tuples with specific element types and lengths.
   type Point = [number, number];

   const coordinates: Point = [10, 20];
Enter fullscreen mode Exit fullscreen mode

In general, interfaces are often preferred for defining object shapes, while types are more versatile and can be used for a wider range of scenarios. The choice between them often comes down to personal preference or specific use cases. It's common to see a mix of interfaces and types in a TypeScript codebase.

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