Obtaining the return type of a function

Viewed 109998

I have the following function:

function test(): number {
    return 42;
}

I can obtain the type of the function by using typeof:

type t = typeof test;

Here, t will be () => number.

Is there a way to obtain the return type of the function? I would like t to be number instead of () => number.

8 Answers

The easiest way in the TypeScript 2.8:

const foo = (): FooReturnType => {
}

type returnType = ReturnType<typeof foo>;
// returnType = FooReturnType

Use built-in ReturnType:

type SomeType = ReturnType<typeof SomeFunc>

ReturnType expands to:

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

The code below works without executing the function. It's from the react-redux-typescript library (https://github.com/alexzywiak/react-redux-typescript/blob/master/utils/redux/typeUtils.ts)

interface Func<T> {
    ([...args]: any, args2?: any): T;
}
export function returnType<T>(func: Func<T>) {
    return {} as T;
}


function mapDispatchToProps(dispatch: RootDispatch, props:OwnProps) {
  return {
    onFinished() {
      dispatch(action(props.id));
    }
  }
}

const dispatchGeneric = returnType(mapDispatchToProps);
type DispatchProps = typeof dispatchGeneric;

I came up with the following, which seems to work nicely:

function returnType<A, B, Z>(fn: (a: A, b: B) => Z): Z
function returnType<A, Z>(fn: (a: A) => Z): Z
function returnType<Z>(fn: () => Z): Z
function returnType(): any {
    throw "Nooooo"
}

function complicated(value: number): { kind: 'complicated', value: number } {
    return { kind: 'complicated', value: value }
}

const dummy = (false as true) && returnType(complicated)
type Z = typeof dummy
Related