乐闻世界logo
搜索文章和话题

What is the difference between type and interface in Typescript?

1个答案

1

Similarities

  1. Defining Shape: Both can be used to describe the shape of an object or function.
  2. Extensibility: Both support extension (type through intersection types, interface through inheritance).

Differences

  1. Extensibility:

    • Interface: Interfaces support open-ended extension, meaning within the same scope, the same interface can be declared multiple times, and these declarations will automatically merge.
    • Type: Type aliases do not support open-ended extension, and once declared, a type alias cannot be redeclared.

    Example:

    typescript
    interface Person { name: string; } interface Person { age: number; } // Person interface automatically merges to: // interface Person { // name: string; // age: number; // } type Animal = { name: string; } // The following would cause an error, as type aliases cannot be redeclared // type Animal = { // age: number; // }
  2. Use Cases:

    • Interface: Better suited for defining the shape of public APIs, as it is easier to extend and reuse in declaration files.
    • Type: Due to its support for more complex type operations like union types and intersection types, it is more appropriate for type composition or other complex type scenarios.

    Example:

    typescript
    type Pet = { name: string; } & { onWalk: () => void; }; type CatOrDog = 'cat' | 'dog';
  3. Declaration Merging:

    • Interface: Supports declaration merging, as shown in the previous example.
    • Type: Does not support declaration merging.

Conclusion

When choosing between type and interface, if you need to define type compositions or leverage union types, type is the better choice. If your primary goal is object-oriented programming and you might need to merge definitions from different places, then interface is more suitable. In many cases, both can be used interchangeably; the choice largely depends on personal or team preferences and specific circumstances.

2024年6月29日 12:07 回复

你的答案