In software development, we’re always striving to create components that are reusable, architectures that can adapt to multiple situations and we’re always looking for a way to automate our logic in a way that it can behave correctly even upon the face of the unknown.

And although that might not always be easy or even doable in some situations, our mindset is always set to find patterns that can be reproduced and then turned into a generic algorithm that will be able to tackle it. And the concept of _Generics _is another example of that behavior, only this time, instead of going macro, we’re going micro and we’re trying to find and represent patterns at the code level.

Let me explain…

What are Generics?

The concept of Generics is a fun one once you’re able to wrap your head around it, so let me just start by putting it like this:

Generics are to Types, what Types are to Variables

In other words, Generics provide you with a way of using Types without having to specify one. This provides a new level of flexibility over your Functions, Classes, and even Interface definitions.

The classic example of this used to explain the power of a Generic, is the identity function. This function essentially returns whatever you pass as a parameter, there is nothing fancy about, but if you think about it, how can you define such a function in a typed language?

function identity(value: number):number {
  return value;
}

The above function works great for numbers, but what about strings? Or booleans? What about custom types? These are all possibilities inside TypeScript, so the obvious choice is to go with the any type:

function identity(value: any): any {
  return value
}

This works, kinda, but now your function has actually lost all concept of type, you’re not able to use the information of the actual type used for anything. Essentially you can now write something like this and the compiler will not say anything, it’ll be just like if you were using plain JavaScript (i.e with no type information whatsoever):

let myVar = identity("Fernando")

console.log(myVar.length) //this works great!

myVar = identity(23)

console.log(myVar.length) //this also works, although it prints "undefined" 

Now since we don’t have type information, the compiler is unable to check anything related to our function and our variable, thus we’re running into an unwanted “undefined” (which if we extrapolate this example into a real-world scenario with more complex logic would probably turn into the worst problem).

How do we fix this then and avoid using the any type?

#typescript #web-development #javascript #programming

TypeScript: The Value of a Good Generic
2.15 GEEK