I have the following function:
function test(): number {
return 42;
}
I can obtain the type of the function by using typeof
Edit: This is not needed with TS 2.8 any more! ReturnType
gives the return type. See accepted answer.
A variant on some of the previous answers that I'm using, which works in strictNullChecks
and hides the inference gymnastics a bit:
function getReturnType(fn: (...args: any[]) => R): R {
return {} as R;
}
Usage:
function foo() {
return {
name: "",
bar(s: string) { // doesn't have to be shorthand, could be `bar: barFn`
return 123;
}
}
}
const _fooReturnType = getReturnType(foo);
export type Foo = typeof _fooReturnType; // type Foo = { name: string; bar(s: string): number; }
It does call the getReturnType
function, but it does not call the original function. You could prevent the getReturnType
call using (false as true) && getReturnType(foo)
but IMO this just makes it more confusing.
I just used this method with some regexp find/replace to migrate an old Angular 1.x project that had ~1500 factory functions written like this, originally in JS, and added the Foo
etc types to all uses... amazing the broken code one will find. :)