Difference between TypeScript Class and Interface
Class
TypeScript is an object-oriented JavaScript language, which supports programming features like classes, interfaces, polymorphism, data-binding, etc. TypeScript support these features from ES6 and later version.
Classes are the fundamental entities which are used to create reusable components. It is a group of objects which have common properties. In terms of OOPs, a class is a template or blueprint for creating objects. It is a logical entity.
We can define the following properties in a class definition:
Fields: It is a variable declared in a class.
Methods: It represents an action for the object.
Constructors: It is responsible for initializing the object in memory.
Nested class and interface: It means a class can contain another class.
Syntax to declare a class
We can declare a class by using the class keyword in TypeScript. The following syntax explains the class declaration.
To read more information, click here.
Interface
An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow, means a class which implements an interface is bound to implement all its members. We cannot instantiate the interface, but it can be referenced by the class object that implements it.
The interface contains only the declaration of the methods and fields, but not the implementation. We cannot use it to build anything. A class inherits an interface, and the class which implements interface defines all members of the interface.
When the Typescript compiler compiles it into JavaScript, then the interface will be removed from the JavaScript file. Thus, its purpose is to help in the development stage only.
Interface Declaration
We can declare an interface by using the interface keyword in TypeScript. The following syntax explains the interface declaration.
Use of Interface
We can use the interface for the following things:
- Validating the specific structure of properties
- Objects passed as parameters
- Objects returned from functions.
To read more information, click here.
TypeScript class vs. TypeScript Interface
TypeScript Class | TypeScript Interface |
---|