Why You Should Consider Using TypeScript Generics Instead of Any
A quick overview of a powerful feature
In this article, we will briefly go over how we can enhance our code base by using generics instead of ignoring the types by using any.
If you are experienced with server-side languages, such as C#, Java, etc., you would already have an understanding or at least been introduced to how it works.
Take, for example, the function below:
Now, that is a basic function. Our definition is simply to add two variables.
If the variables are numeric, it will do a mathematical addition and return the sum. However, if at least one of the variables is a string, it will concatenate it and return a string.
When we hover to get some type of help, we would see:
By default, TypeScript types variables as
any because every variable must have a type. The type
any basically says that, once a variable or function has this type, the compiler should not type-check it.
Though this can be very tempting to use, I would highly encourage and recommend you not to use it. Of course, there are edge cases where it’s more convenient to use
any instead of writing a convoluted type check. However, the first approach is to assign a proper type.
Now, let’s assume that we want to keep the same function structure but allow the consumer of the function to define which type it should return.
It’s quite hard to do this, however. Here is what you need to do:
Now, look at what happens when we hover:
As you can see, all we do is define an arbitrary type as
R and then tell the function that our return type will be that same
This way, whoever consumes it, can define the return type themselves and it is guaranteed to have that return type after the function has returned!
As you can see, both use the same function, however, the resulting
type is not identical as the consumer has changed the return type without touching the function definition.
Please Note: These are not real-world examples and are only used to expose the generic functionality.😅
It is just the tip of the iceberg! There are many more ways to apply this functionality such as functions, interfaces, classes, keys, objects, etc. This is the power of generics.
Instead of using
any and ignoring the type, enforce it and use it to your advantage. This will help you and others that are either reading or consuming your codebase in some way.
Additionally, it enhances your testing abilities because it was a great way to construct a “meta” function, without changing the definition but having a consumer-defined result type.
You can learn more about generics by reading the TypeScript Hand Book.