Interfaces

An interface provides us with a mechanism to define what properties and methods an object must implement, and is, therefore, a way of defining a custom type. We have already explored the TypeScript syntax for strongly typing a variable to one of the basic types, such as a string or number. Using this syntax, we can also strongly type a variable to be of a custom type, or more correctly, an interface type. This means that the variable must have the same properties as described in the interface. If an object adheres to an interface, it is said that the object implements the interface. Interfaces are defined by using the interface keyword.

To illustrate the concept of interfaces, consider the following code:

interface IComplexType { 
    id: number; 
    name: string; 
} 

We start with an interface named IComplexType that has an id and a name property. The id property is strongly typed to be of type number, and the name property is of type string. This interface definition can then be applied to a variable, as follows:

let complexType : IComplexType; 
complexType = { id: 1, name : "test" };

Here, we have defined a variable named complexType, and strongly typed it to be of type IComplexType. We are then creating an object instance, and assigning values to the object's properties. Note that the IComplexType interface defines both an id and a name property, and as such both must be present. If we attempt to create an instance of the object without both of these properties, as follows:

let incompleteType : IComplexType; 
incompleteType = { id : 1}; 

TypeScript will generate the following error:

error TS2322: Type '{ id: number; }' is not assignable to type 'IComplexType'.
Property 'name' is missing in type '{ id: number; }'.