Function with dynamically typed parameters, in Typescript.
Guilherme Niches
Posted on November 8, 2022
In Typescript, how to create a function that returns the type that itself receives?
If we don't explicitly set the parameter the function returns an 'any' type.
If we set it, the function returns the fixed type in the parameter.
So, how to handle it? Let's see.
In the below example, we declare a function that receives a parameter and returns the parameter itself. This parameter was not explicitly set, so when we call the function, the returned value has an 'any' type.
But, wait... We passed a number as a parameter to our function and this function just returns this parameter, so, the value should be a number, right? Well, unfortunately, the Typescript "doesn't understand" it in this way.
To handle with this, we can use Generics of Typescript.
Generics in Typescript
Okay, so we will use Generics, but what is Generics?
The Typescript documentation explains Generics as:
"(...) being able to create a component that can work on multiple types rather than a single one."
Refactoring the code, our function now received the type variable Type, a kind of variable that works on types rather than values. This Type allow us to capture the type that the user inform. And in this example, we declare this Type as the type of the return of the function.
So, if we pass a number to our function it will return a number, if we pass a string it will return a string, if we pass an object with some attributes (like as example above), it will return the object with the typed values. The same goes for array and other types.
Concluding
In this way, our function will apply types regardless of what we pass as a parameter. This allows us to create functions that can be used in different contexts, turning the function more reusable.
It is worth mentioning that, despite this feature of Typescript, it is always interesting to try to be declarative in your typing. So, this is a feature to use with prudence.
References
Posted on November 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.