DEV Community

Guilherme Niches
Guilherme Niches

Posted on

Function with dynamically typed parameters, in Typescript.

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.

example.ts

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.

example.ts

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

Top comments (4)

Collapse
 
crhist0 profile image
Crhistian de Oliveira

Great article, thank you Guilherme.

Collapse
 
gniches profile image
Guilherme Niches • Edited

Hello, Crhistian. I'm glad to see you here, thank you for reading my first article. :))

Collapse
 
edsonlnunes profile image
Édson Martins

Very interesting topic, very good!

Collapse
 
gniches profile image
Guilherme Niches

Thank you, Édson. I'm honored that you liked it.