TypeScript Generic Types

Alaa Chakroun
eDonec
Published in
3 min readApr 30, 2021

TypeScript taken to the next level

Photo by Bernard Hermant on Unsplash

As of late, TypeScript has seen a huge adoption as seen in various stats and many developpers agree that once they tried the type strict system of TypeScript, it’s hard to go back to the more conventional (and chaotic) JavaScript. In this article, we are going to explore an underrated feature of TypeScript (Type Generics) and learn where, when and how to use them.

The issue at hand:

While working with TypeScript, we often write functions like the following image, which is perfectly fine, but doesn’t quite use the full power of TypeScript and intellisense.

The function above works as expected, as long as we pass a key that exists in the data object, but nothing stops us doing otherwise.

More importantly, nothing tells the TypeScript compiler that something’s wrong as seen below (nonExistingValue is typed as string)

This is where TypeScript generics come in handy.

The Solution

What are TypeScript generics ?

TypeScript generics is basically a way to pass arguments to a TS type or interface. The type can be used for some logic to deduce the correct return type. This may sound complicated at first so let’s take a simple example : a TypeScript type that returns the type passed as “argument”.

sounds easy enough? Well, TypeScript generics can also be used in functions either implicitly or explicitly.

And taking a look at our IDE shows us the following error that we expected.

Implementing the solution :

Now that we took a first look at TypeScript generics, let’s use them to fix our first issue in the getValue function.

We transformed the getValue function to accept a generic type as its data input, and use this type’s keys as a type for the key argument using the keyof type operator. This basically solves all the issues we had as well as provides helpful intellisense in the IDE.

Visual Studio Code Intellisense
TypeScript Error

Final Words

As we saw in this article, using TypeScript generics helps us write less error-prone, more maintainable and refactorable code as well provide a better developper experience with intellisense integration in the IDE.

This has been developed by myself at eDonec .

--

--