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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video