Member-only story
Extending TypeScript Generics for Additional Type Safety
Take your TypeScript polymorphism up a notch

Generics is one of the more complicated aspects of TypeScript, so baby steps are important. In this article, I’ll do some quick examples of how to do more advanced maneuvers by extending your generic types.
If you aren’t already familiar with the concept of generics, I recommend you first read my Brief Intro to TypeScript Generics article and then continue here.
Welcome back!
Let’s say we have a class of type Menu
that looks like this:
Let’s also say that we have the following types of items:
From the above we could instantiate a food or a drink menu like this:
const drinkMenu = new Menu<Drink>();
const foodMenu = new Menu<Food>();
The generics here ensure that each one of those menus can only contain the type of item they’re supposed to. If I try to add a hamburger to the drink menu, then TypeScript is going to yell at me.

So that’s working out great! The problem is that I could also potentially create a Waiter
menu, and that would just be plain weird.
const waiterMenu = new Menu<Waiter>(); // WTF?!?!?
So how can we prevent this? Easy! We will go back to our original menu definition and add some constraints around our generic.