Typescript Interfaces – Part 3 Extends

 

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

In the third series, we’re going to cover extending, or otherwise known as inheritance. This comes from the core of the object orientated paradigm.

Inheritance is the key stone of how typescript works, but we won’t dive into that right now.

Scenario: you have interface a, and now you want to add a property to it for one specific variable, except you can’t because typescript throws an error, usually something like “Property x does not exist on type y”. Overcoming this is easy enough, but very frustrating if you’re coming from javascript.

Now there are a ton of hacky answers on stackoverflow, such as setting type to any. Which can be done like so.


let mermaid:any = {
    // add any properties you lile, it's not typed now
}

But this is usually very bad practice, though in some instances the only viable workaround. However, in our case we can simply extend our interface. So lets say we have an interface animal, and it describes some properties of an animal. Then we went to make an animal, and give it some properties that belong to a fish. Well for that, we can just extend our animal interface, and make a fish interface.


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

declare interface iFish extends iAnimal {
    freshWater: boolean;
}

let salmon: iFish = {
    weight: 120,
    species: 'fish',
    freshWater: true
}

Okay, that’s all fine.. but wait, what? Why?!

I’m not saying it’s inheritance, but.. it’s inheritance! The iFish interface literally inherits all the properties of the iAnimal. So when using the type iFish, you are also gaining all of the attributes of iAnimal. This is exactly the same way you would extend classes in typescript, or indeed any other language.

Still with me? Okay, so lets say you want to make an amalgamation interface, where you inherit multiple interfaces.

It’s actually very easy, and readable. Just list all the interfaces you wish to extend, separated by a comma.


declare interface iBuilding extends iFoundations, iStructure, iLighting {

}

and now, your iBuilding will have all the properties of iFoundation, iStructure, iLighting.

Simple enough? Great, then lets jump on over to implementing interfaces. (kind of the same thing, but not really)