Interfaces
In Chapter 1, Up and Running Quickly, we discussed how TypeScript uses duck typing to assess if two objects are compatible. These typing rules govern whether an object can be assigned to another and compares the properties of one object to the other.
Interfaces provide us with a mechanism to define what properties an object must implement and is, therefore, a way for us to define a custom type. By defining an interface, we are describing the properties and functions that an object is expected to have in order to be used by our code.
To illustrate these concepts, consider the following code:
interface IIdName {
id: number;
name: string;
}
Here, we have used the interface
keyword to define a TypeScript interface named IIdName
. This interface describes an object that has an id
property of type number, and a name
property of type string. Once we have defined an interface, we can use it in the same way as a primitive type, as follows:
let idObject...