Why you should use generic types in TypeScript, a simple example

Image for post
Image for post

TypeScript has a steep learning curve, at least for me, for a front-end developer used to write without types sometimes I struggled to change my way of thinking to my code.

When people used syntax like <T extends key of P> in StackOverflow answers, I have always been fascinated yet scared so I decided to put down a simple example to help people like me to become a “cool guy”.

First of all, let’s say we want to have a TypeScript function which receives an array of objects and filters this array by a single property value:

So now we have a function that filters an array of Book and returns a filtered array of Book based on the property and the value we pass in the second and third parameters.

Let’s say we have another type called Car and we want to use the same function to filter a list of Car[], right now we will trigger an error.

Our function this way is not reusable, what we can do is use a generic type T instead of a defined type like Book:

We now have a reusable function and we can use it with any entity that meets our type condition.

We can still write a better function, in our case we want the propertyName to be the name of a property contained in the type of T, plus we want the value to filter to be a partial value of the entity T. We can introduce another generic type which extends T, called P to tell TypeScript we want to use a property of T as the second parameter:

Last we can now define the valueToFilter parameter as following:

in our case valueToFilter is a partial value of T, so we can also define it as follows:

Here is our final function:

Here is our final code:

That’s it! Thank you if you arrived so far, understanding the concepts above gave me a great understanding of TS world, I hope you found it helpful!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store