TypeScript中interface和abstract class区别

208 阅读1分钟

In TypeScript, an interface and an abstract class are similar in that they both define a structure that can be implemented by classes. However, there are some key differences:

  1. Implementation - An abstract class can have its own implementation for certain methods, while an interface cannot. In other words, an interface only describes what an object should have, while an abstract class defines how it should work.
  2. Constructors - Abstract classes can have constructors, while interfaces don't.
  3. Inheritance - A class can inherit from multiple interfaces, but can only inherit from one abstract class.
  4. Access modifiers - Abstract classes can have access modifiers (public, private, protected) on their members, while interfaces only have public members.
  5. Instantiation - Abstract classes cannot be instantiated directly, whereas interfaces have no implementation and can't be instantiated.

In summary, interfaces are used to define a set of methods and properties that a class should implement, while abstract classes provide a template for concrete classes to extend and implement its methods and properties.