What is the difference between using TypeScript interface and type for defining types?

What is the difference between using TypeScript interface and type for defining types?

For example, consider the following statements:

interface X {
    a: number;
    b: string;
}

type X = {
    a: number;
    b: string;
};

Could anyone explain the distinctions between these two approaches?

Interface supports declaration merging, allowing you to define multiple interfaces with the same name and automatically combine their members. This is useful for extending or augmenting existing interfaces.

For example:

interface X {
    a: number;
}

interface X {
    b: string;
}

// Resulting type: { a: number; b: string; }

In contrast, type does not support declaration merging. If you try to declare a type with the same name more than once, TypeScript will throw an error.

Hi,

type can represent union and intersection types, which allows for more complex type compositions.

For example:

type A = { a: number; };
type B = { b: string; };

type X = A & B;  // Intersection type: { a: number; b: string; }

type Y = A | B;  // Union type: { a: number; } | { b: string; }

Interface does not support union types directly, though you can achieve similar effects through interface extension and merging.

Interface is generally used for defining object shapes and can be extended by other interfaces or classes. It is specifically designed for object-oriented programming patterns.

On the other hand, type is more flexible and can represent not just object shapes but also primitives, tuples, and more complex types:

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

type Animal = {
    species: string;
    age: number;
};

type UnionType = Person | Animal;  // Union of Person and Animal types