Interfaces in typescript

May 04, 2020

The interface is a great Typescript feature and helps to write clearly structured and explicit code.

The interface helps you to describe a structure like fields without values and methods without implementation.

The interface also to force objects and class to have his implementation as a contract, if the object or class use the interface must to implement all field and methods required.

Interface as Type

The interfaces are created with interface keyword and contain the blueprint of an object, for example, Subscription, contained properties and methods.

And also allow mark as optional properties or methods adding a question mark after the method name or property.

interface Subscription {
	readonly: id;
	url?: string;
	name: string;
	sign() ?: string;
}

Using the interface as a type.

let  subscriptionFrench : Subscription = {
	id: 1
	name: 'Paris',
	sign(): string {
		return "Bonjour"¨;
	}
}

Implement interfaces in classes

The interface also helps to force your classes or your objects to have a structure and to clearly describe how an object should look like.

Using implement keyword after the class name and the name of the interface the class will implement the interface and must have every field defined into the interface.

Also, the class can implement more than one interface, separate by commas it an advance over normal inherits.

The IDE and compiler will raise an error if it doesn’t fit with the interface.

interface NetflixPremium  {
  allMovies: number;
}
class Spain implements NetflixPremium, Subscription {
    price: Number = 10.99;
    allMovies: number = 100;
    constructor(public name: string) {

    }
    sign(): void {
        console.log(`Thanks for signup ${this.name}.`)
    }
}

let spainSubscriptions = new Array<Spain>();
let bcn = new Spain("bcn");
let madrid = new Spain("madrid");

spainSubscriptions.push(bcn);
spainSubscriptions.push(madrid);

spainSubscriptions.forEach(element => {
    element.sign();
});

Extends interfaces

A better way to implement multiples interfaces in a single class is by extending interfaces using the extends keyword and the name of the interface to be extended.

interface NetflixPremium extends Subscription {
  allMovies: number;
}

The interface NetflixPremium contains every related to Subscription and the class Spain only needs to implement a single interface.

class Spain implements NetflixPremium {
    price: Number = 10.99;

    constructor(public name: string) {

    }
    sign(): void {
        console.log(`Thanks for signup ${this.name}.`)
    }
    allMovies: number = 100;

}

That’s it!

Hopefully, that will give you a bit of help with interface in Typescript. If you enjoyed this post, share it.