Interfaces in TypeScript
Learn how to create and use interfaces in TypeScript.
We'll cover the following...
As applications scale and more classes are created, we need to find ways to ensure consistency and rule compliance in our code. One of the best ways to address the consistency and validation of types is to create interfaces. An interface is a code contract that defines a particular schema. Any artifacts such as classes and functions that implement an interface should comply with this schema. Interfaces are beneficial when we want to enforce strict typing on classes generated by factories or when we define function signatures to ensure that a particular typed property is found in the payload.
In the following snippet, we define the Vehicle
interface:
interface Vehicle {make: string;}
Any class that implements the preceding interface must contain a member named make
, which must be typed as a string
:
class Car implements Vehicle {make: string;}
Interfaces are also beneficial for defining the minimum set of members any artifact must ...