TypeScript provides some handy methods to facilitate type transformations. One of them is ReturnType, which allows us to get the return type of a function, which can be useful to avoid hardcoding types in your code that can break at any moment.
Continue reading to learn how to use the ReturnType function.
Use the ReturnType utility:
function sayHi(name: string) {
return `Hi, ${name}!`
}
sayHi('Giovanni') // Hi, Giovanni!
type SayHiReturnType = ReturnType<typeof sayHi> // string
Let's start with a simple function that returns a string:
function sayHi(name: string) {
return `Hi, ${name}!`
}
sayHi('Giovanni') // Hi, Giovanni!
To get the return type of the sayHi function, we could use the ReturnType utility provided globally by TypeScript:
type SayHiReturnType = ReturnType<typeof sayHi>
SayHiReturnType value will be the string type.
We need to update our code a bit to work with promises.
function sayHi(name: string) {
return Promise.resolve(`Hi, ${name}!`);
}
type SayHiReturnType = ReturnType<typeof sayHi>
Now, SayHiReturnType is equal to Promise<string>, which may not be what we are expecting.
If we want to get the return type of our function, we need to use the Awaited utility:
type SayHiReturnType = Awaited<ReturnType<typeof sayHi>>;
Now SayHiReturnType has a value of string.
TypeScript has powerful yet simple utility functions like ReturnType that we can use to build resilient applications.
Start using them and you'll notice how you'll need to do less changes when updating something.
You can DM on Twitter if you have any question or just want to say hi 😄 I'll be glad to talk with you!