returnof
returnof copied to clipboard
TypeScript typeof function return helper
returnof
A workaround to get the return type of a function in TypeScript.
DEPRECATED
Since TypeScript 2.8, and thanks to new Conditional Types and infer keyword, a ReturnType is now directly available in the language, permitting to get the return type of a function in a fully declarative way.
Usage
const hello = () => ({ hello: 'World' })
type HelloReturn = ReturnType<typeof hello>
Locked in the Past?
If for some strange reason you cannot upgrade to TypeScript 2.8+:
(Some teams stay locked in the past for a while)
It's gonna be really hard waiting 30 years before I can talk to you about everything that's happened in the past few days. I'm really gonna miss you, Marty.
– Dr. Emmett "Doc" Brown
Install
npm install returnof
Function return type
At the moment TypeScript does not allow to get the return type of a function.
const hello = () => ({ hello: 'World' })
type helloReturnType = typeof hello() // ERROR
returnof allows you to get it, at the cost of (a little) more verbosity.
import returnof from 'returnof'
const hello = () => ({ hello: 'World' })
const helloReturnValue = returnof(hello)
type helloReturnType = typeof helloReturnValue // { hello: string }
At runtime, helloReturnValue will be null.
Overloaded functions
If your function is overloaded and there is an ambiguity on which one you're trying to get the return type, you can pass additional arguments:
declare function hello(): void;
declare function hello(a: number): number;
const helloReturnValue = returnof(hello)
type helloReturnType = typeof helloReturnValue // void
const helloReturnValue = returnof(hello, 42)
type helloReturnType = typeof helloReturnValue // number
If there's no ambiguity, you do not need to pass additional arguments:
declare function hello(a: number): number;
const helloReturnValue = returnof(hello)
type helloReturnType = typeof helloReturnValue // number
