Sobes.tech
Middle

When should you use types and when interfaces in TypeScript?

sobes.tech AI

Answer from AI

Types (type) should be used for:

  • Unions and intersections:
    type Status = "pending" | "completed" | "failed";
    type UserWithAddress = User & Address;
    
  • Primitive types and literals:
    type ID = string | number;
    type Direction = "up" | "down" | "left" | "right";
    
  • Tuples:
    type RgbColor = [number, number, number];
    
  • Creating aliases for existing types:
    type StringOrNumber = string | number;
    
  • Conditional types:
    type TypeOfProp<T, K extends keyof T> = T[K];
    

Interfaces (interface) should be used for:

  • Describing object structures:
    interface User {
      id: number;
      name: string;
      age?: number; // Optional property
    }
    
  • Implementations with classes (implements):
    interface Logger {
      log(message: string): void;
    }
    
    class ConsoleLogger implements Logger {
      log(message: string) {
        console.log(message);
      }
    }
    
  • Extending other interfaces (extends):
    interface Person {
      name: string;
    }
    
    interface Employee extends Person {
      employeeId: number;
    }
    
  • Declaration merging: This allows extending an existing interface by declaring it again. This is not possible with types.
    interface Box {
      width: number;
    }
    
    interface Box { // This will add a height property to the Box interface
      height: number;
    }
    

Brief comparison:

Feature type interface
Union types Yes No
Intersection types Yes No
Primitive types/Literals Yes No
Tuples Yes No
Type aliases Yes No
Conditional types Yes No
Object description Yes Yes
Class implementation No Yes
Extension Yes (using &) Yes (using extends)
Declaration merging No Yes

Overall, for describing object structures, interface is preferable as it better suits object-oriented approaches and supports declaration merging. For everything else, especially for combining and creating new types from existing ones, type is more flexible.