Extend interfaces in Typescript

Interface an interface. If that doesn’t excite you, I don’t know what will.

We have seen interfaces used as types before. But as our God Goop says - “abstract; (while && when) you can;“. So, we are here to know about interfaces for interfaces.

Consider this simple example -

interface Borg {
  name: string;

Now, any class implementing the interface Borg will have a name attribute.

What if you want to add more attributes? Well, you can always add attributes to Borg, but what if you have a function that very much likes names and cannot digest anything else?

Or, you have security rules requiring you to obfuscate or hide stuff?

In all those cases and because we like to build incrementally and in a layered fashion, we should be looking at interfaces to interfaces.

For example -

interface Borg {
  name: string;

interface Borger {
  ssn: string;

Now, we could have an object implementing Borg or Borger.

const bo1: Borg = {
  name: "Queen"

const co1: Borger = { name: "Queen", ssn: "collective" };

Borger must have ssn from parent interface and name from the inherited interface.


The conversation at this point will be something like -

You: “Ok guy, I am excited. Let’s derive some interfaces”.

Me: “You crazy? Why do you think I give names like ‘Borg’ to the poor objects. Be careful about joining the collective.”

In reality: I don’t typically use interfaces on interfaces on interfaces. I am just not fixated enough on object oriented patterns even after two decades of working with them.

comments powered by Disqus