Typescript中interface和class的区别

85 阅读1分钟

In TypeScript, an interface is a structural definition that describes the shape of an object. It defines the properties, methods, and types of an object, but does not provide an implementation for these members.

A class, on the other hand, is a blueprint for creating objects that defines the properties, methods, and behavior of those objects. It provides both a definition and an implementation for these members.

Here are some key differences between the two:

  • A class can have a constructor, which is called when creating an instance of the class. An interface cannot have a constructor.
  • A class can define public and private members, whereas an interface can only define public members.
  • A class can implement multiple interfaces, while an interface cannot extend a class or another interface.
  • An instance of a class is created with the "new" keyword, while an interface cannot be instantiated directly.

In summary, an interface defines a contract that objects can implement, while a class provides a concrete implementation of that contract.