Interfaces – TypeScript Patterns for Angular
In TypeScript, we have another way of typifying the structure of an object called an interface. The following example demonstrates its use:
export interface Animal {
species: string;
kingdom: string;
class: string;
}
To declare an interface, we use the reserved word interface and declare its properties as a class as we saw earlier.
To use interface, we can proceed as follows:
import { Animal } from “./animals”;
export function basic_interface() {
let chicken: Animal = {
kingdom: “Animalia”,
species: “Gallus”,
class: “birds”,
};
console.log(kingdom:${chicken.kingdom} species:${chicken.species} class:${chicken.class}
);
}
Note that to use a class, we just type the variable and declare its values, without using the reserved word new. This happens because the interface is not a JavaScript element and is only used by the TypeScript transpiler to check whether the object contains the defined properties.
To prove that the interface does not exist, if we transpile the interface file, a blank file will be generated by TypeScript!
We can also make use of interfaces to create contracts for classes, should a class require certain methods and attributes. Let’s see the following example:
export interface Animal {
species: string;
kingdom: string;
class: string;
}
export interface DoSound {
doASound: () => string;
}
export class Duck implements DoSound {
public doASound(){
return ‘quack’;
}
}
export class Dog implements DoSound {
public doASound(){
return ‘bark’;
}
}
To define that a certain class follows the DoSound contract, we use the reserved word implements. TypeScript then requires that a method called doASound be defined and that this method returns a string.
This feature of the interface facilitates the use of a very important capability of the object-oriented language, which is polymorphism. Let’s see the example:
export function animalDoSound() {
let duck = new Duck();
let dog = new Dog();
makeSound(duck);
makeSound(dog);
}
function makeSound(animal: DoSound) {
console.log(The animal make this sound:${animal.doASound()}
);
}
We create the makeSound function, which receives an animal that implements the DoSound contract. The function is not concerned with the type of animal or its attributes; it just needs to follow the DoSound interface contract, as it will invoke one of its methods.
Angular uses this characteristic of TypeScript interfaces a lot, as we can see in the declaration of a component:
export class SimulationComponent implements OnInit {
When we inform Angular that the component implements the OnInit interface, it will execute the ngOnInit method required at the beginning of the component’s lifecycle (we will study this in more detail in Chapter 4, Components and Pages).