Typescript Interfaces – Part 4 Implements

 

If you are new to interfaces, go and checkout part 1 of series of articles on typescript interfaces or go here for part 2 or part 3.

In the fourth instalment, we’re going to touch on the keyword, implements, which is a sort of inheritance. So you already understand extending? great, then this follows the same path.

Lets propose you have an interface, and instead of typing an object, you want to type a class. Well, that, in a nutshell, is implementation. You would simple declare your class and implement your interface. Now your class has to contain those properties else typescript will throw an error. Lets go back and grab the animal – fish example from the previous article.


declare interface iAnimal {
    weight: number;
    species: string;
}

declare interface iFish extends iAnimal {
    freshWater: boolean;
}

class Salmon implements iFish {

    public weight: number;
    public species: string;
    public freshWater: boolean;

    constructor(weight: number, species: string, freshWater: boolean) {

    }
}

Now all we’ve done, is said that class Salmon must have at LEAST the properties of the fish. It does not say you cannot add more. Also, something worth mentioning, you must use properties as public, if they are inherited from an interface.

So you could, for instance, go ahead and give your Salmon a name property, and it would be perfectly acceptable. When extending this class, your new class will also inherit the properties of iFish, naturally.

But it gets even better, what if you want to make a class that is made up of many interfaces, typescript says no problem! Just simply list them in order, comma separated as an implementation. Like so,


class Car implements iEngine, iGearbox, iChassis...

And that just about covers it for interfaces. Or at least as far as I know. If I’ve missed something, please just drop a comment and I’ll be sure to fix or add anything I’ve missed.

Stay tuned for some more typescript tutorials.