Why to use type over interfaces in Typescript

In TypeScript, both type and interface are used to define custom types, but they have some differences and specific use cases where one might be preferred over the other.

When to Use type Over interface

  1. Union Types:

    type can represent union types, where a type can be one of several possible types.

    Example:

    type Status = "success" | "failure" | "pending";
    
  2. Intersection Types:

    type can be used to combine multiple types into one using the & operator.

    Example:

    type Admin = {
      name: string;
      role: "admin";
    };
    
    type User = {
      name: string;
      role: "user";
    };
    
    type AdminUser = Admin & User;
    
  3. More Complex Types:

    type can handle more complex types, such as tuples, mapped types, and more.

    Example:

    type Point = [number, number];
    
  4. Primitive Types:

    type can create an alias for any kind of type, including primitives.

    Example:

    type ID = string | number;
    
  5. Cannot be Merged:

    Unlike interface, type cannot be merged or extended by subsequent declarations, making it safer in scenarios where you don't want unintended extension or merging.

When to Use interface

  1. Object Type Declarations:

    interface is more suited for defining the shape of an object, particularly when you want to describe an object with methods.

    Example:

    interface User {
      name: string;
      age: number;
      greet(): void;
    }
    
  2. Extending and Implementing:

    interface supports easy extension and can be implemented by classes.

    Example:

    interface Animal {
      name: string;
      makeSound(): void;
    }
    
    interface Dog extends Animal {
      breed: string;
    }
    
  3. Declaration Merging:
    interface can be merged with another interface of the same name, which can be useful in extending third-party types.

    Example:

    interface User {
      name: string;
    }
    
    interface User {
      age: number;
    }
    
    const user: User = {
      name: "Alice",
      age: 30,
    };
    

Summary

  1. Use type when you need to create more complex types, such as unions, intersections, or primitive type aliases.
  2. Use interface when you are defining the shape of an object, especially if you plan to use classes or need the flexibility of extension and merging.