Obtaining the return type of a function

前端 未结 7 2327
既然无缘
既然无缘 2020-12-02 08:56

I have the following function:

function test(): number {
    return 42;
}

I can obtain the type of the function by using typeof

7条回答
  •  渐次进展
    2020-12-02 09:41

    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. :)

提交回复
热议问题