To easily make a type from the function's return value in TypeScript, you can use the ReturnType
utility type and pass the function type declaration which you need to get the type of return value from as the first type argument.
TL;DR
// a simple function that has
// an infered type of `string`
function sayGreeting(name: string, greeting: string) {
return `${greeting}, ${name}`;
}
// make type from function's return value
// using the `ReturnType` utility type
type FunctionReturnType = ReturnType<typeof sayGreeting>; // string
Let's say we have a function called sayGreeting
that accepts 2 return value called name
and greeting both having the type of string
like this,
// a simple function that has
// an infered type of `string`
function sayGreeting(name: string, greeting: string) {
return `${greeting}, ${name}`;
}
Now to get the type of return value in the sayGreeting
function, we can use the ReturnType
utility type and then pass the type of the sayGreeting
function.
Now you might ask how can we get the type of a function, for that we can use a nifty operator called typeof
followed by writing the name of the function. This will automatically infer the function's entire type including the return value type. We can then pass this as the first type argument to the ReturnType
utility type.
It can be done like this,
// a simple function that has
// an infered type of `string`
function sayGreeting(name: string, greeting: string) {
return `${greeting}, ${name}`;
}
// make type from function's return value
// using the `ReturnType` utility type
type FunctionReturnType = ReturnType<typeof sayGreeting>; // string
Now if you hover over the FunctionReturnType
you can see the type as string
which is exactly the return type of the sayGreeting
function.
We have successfully made a type from the function return value in TypeScript. Yay π₯³!
See the above code live in codesandbox.
That's all π!
Top comments (0)