[Typescript] Using Type and not Interface in TypeScript

Nên dùng Type hay Interface trong Typescript. Both serve similar purposes, but there are differences between them.

Nên dùng Type hay Interface trong Typescript


Using Type and not Interface in TypeScript

TypeScript offers two main ways to define custom data structures: type and interface. Both serve similar purposes, but there are differences between them that influence when and why you might choose one over the other.

When to Use type:

  1. Unions and Intersections: If you need to create complex types by combining multiple types using union (|) or intersection (&) operators, type is the way to go. type is more flexible when it comes to creating complex and flexible type compositions.

    type Person = { name: string; age: number };
    type Address = { city: string; postalCode: string };
    type Contact = Person & Address;
    
  2. Primitive Types: When defining simple types like strings, numbers, booleans, or literal types, type is often preferred.

    type Status = "active" | "inactive";
    
  3. Mapped Types: If you want to create new types based on the properties of existing types, type is used for mapped types.

    type Optional<T> = { [P in keyof T]?: T[P] };
    
  4. Utility Types: TypeScript provides built-in utility types like Partial, Record, Pick, and Omit that work naturally with type.

    type PartialPerson = Partial<Person>;
    type RecordOfPersons = Record<string, Person>;
    

When to Use interface:

  1. Object Shapes: If you're defining the shape of an object, especially one that represents a class or an instance, interface is a common choice. It's more suited for describing the blueprint of an object.

    interface Person {
        name: string;
        age: number;
    }
    
  2. Class Implementations: When defining the structure of a class, interface is preferred as it can be extended or implemented by classes.

    interface Animal {
        name: string;
        speak(): void;
    }
    class Dog implements Animal {
        constructor(public name: string) {}
        speak() {
            console.log(`${this.name} barks.`);
        }
    }
    
  3. Extending Interfaces: interface can be easily extended to create new interfaces that inherit properties and methods from existing ones.

    interface Employee {
        name: string;
    }
    interface Manager extends Employee {
        department: string;
    }
    
Comment