Looking for a great (remote only) React Dev? Or just feel like having a chat? Visit my profile on LinkedIn and say hi! 😃

Image for post

Probably the most annoying part of my journey with TypeScript has been Generics. The syntax confused me from the start, and the concepts didn’t “naturally” make sense the way that everything else about TypeScript had up until that point.

So I did what every rational procrastinator would do, and tried to avoid the hell out of them… a tactic which failed miserably. Generics are EVERYWHERE, from commonly used libraries like Apollo, to little projects you need to jump onto and help out with, so the only way to deal with them is to learn them, practice using them, and essentially get over any aversion you have to them. _Brute force it — _there’s no other way.

NOTE: I won’t be dealing with Classes in this article, so please refer to the docs if you want to apply Generics to JS Classes.


Generics are like variables, except that instead of representing values, they represent types. E.g.

function getAge<T>(age: T): T {
  return age;
}

const myAge = getAge<number>(40);
console.log(myAge);    // logs 40

Ugly, isn’t it? If code readability is of utmost importance, then how is this an improvement? Well, your guess is as good as mine, so let’s go and drink the TypeScript Kool-Aid together… 😕.

So what’s going on in the code above? First, we declare a function that takes age as a parameter and simply returns it. The angle brackets you see in the beginning <T> means that this function takes a type of T. Because this is a variable, you can then go ahead and use it just like you would any other variable. So we use it to declare that age is of type T and then the function returns a value of type T.

Now, T could be any valid TypeScript basic type. Also, we could use any name or letter, like U or Name. We can even use lower case, like n, although the convention is to use an upper case letter or a word with an upper case first letter — e.g. Key.

We then go ahead and call the function getAge, and now we define what we want T to be — namely number. Finally, we log out myAge and then go and grab a cold beer and quietly cry into it after realizing that we are now officially “mid-life”… 😭🍺🍺🍺

#typescript #generics

TypeScript Generics — The !Easy Way
1.30 GEEK