DEV Community

Cover image for How to easily make a type from a function's return value in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to easily make a type from a function's return value in TypeScript?

Originally posted here!

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
Enter fullscreen mode Exit fullscreen mode

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}`;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 πŸ˜ƒ!

Feel free to share if you found this useful πŸ˜ƒ.


Top comments (0)