Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

Interfaces in Typescript with an Example

Interfaces in Typescript with an Example

Dany Paredes's photo
Dany Paredes
·May 5, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

The interface is an excellent Typescript feature and helps to write structured and explicit code.

The interface helps you describe a structure like fields without values or methods without implementation and forces objects and classes to have.

Interface as Type

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

And also, allow marks 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 clearly describe how an entity should look.

Using implement keyword after the class name and the interface's name, 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 multiple interfaces in a single class is by extending interfaces using the extended keyword and the interface's name to be developed.

interface NetflixPremium extends Subscription {
  allMovies: number;
}

The interface NetflixPremium contains every related to the 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;

}

Done

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

Photo by Cytonn Photography on Unsplash

 
Share this