Level Up TS: Dynamically Extend Interfaces with Generics
ben hultin
Posted on April 4, 2023
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
}
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
}
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)
Here we have learned how to make Generics work for us to implement DRY into our application reducing duplicate code.
Thanks for reading!
π πͺ π
π©
ben hultin
Posted on April 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How I Created Vanilla Calendar Pro β A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024
typescript π₯ Why TypeScript is the Go-To Language for Modern Web Development π₯
October 16, 2024