DEV Community

ben hultin
ben hultin

Posted on • Edited on

Level Up TS: Dynamically Extend Interfaces with Generics

With Typescript you can define what kind of interface or type a function should expect to take in as an argument. This allows you gain control over your application as to what your function will take in or reject.

interface Pet {
  name: string;
  weight: number;
  age: number;
}

function myPet(pet: Pet) {
  // do something with pet
}
Enter fullscreen mode Exit fullscreen mode

What if we have more specific types for pets like birds or cats?

interface Pet {
  name: string;
  weight: number;
  age: number;
}

interface Bird extends Pet {
  wingspan: number;
}

interface Cat extends Pet {
  furType: string;
}

function myBird(bird: Bird) {
  // do something with bird
}

function myCat(cat: Cat) {
  // do something with cat
}
Enter fullscreen mode Exit fullscreen mode

What if we want to combine myCat and myBird so there is just one function?

interface Pet {
  name: string;
}

interface Bird extends Pet {
  wingspan: number;
}

interface Cat extends Pet {
  furType: string;
}

// T refers to either Cat or Bird interfaces
function myPet<T extends Pet>(pet: T) {
  // do something with extended pet
  // pet can either be of type Bird or Cat 
}

const cat: Cat = {
  name: 'Snowball 2'
  furType: 'short'
}

const bird: Bird = {
  name: 'Tweety'
  wingspan: 12
}

// both are now accepted objects to pass into the same function
myPet(cat)
myPet(bird)
Enter fullscreen mode Exit fullscreen mode

Here we have learned how to make Generics work for us to implement DRY into our application reducing duplicate code.

Thanks for reading!

Top comments (0)