Export return type of function in Typescript

后端 未结 1 884
再見小時候
再見小時候 2021-02-20 10:08

I have a function that builds an object, like this:

function toast() {
  return {
    a: \"a\",
    b: \"b\"
  }
}

I can define the type of the

相关标签:
1条回答
  • 2021-02-20 10:30

    Yes it's possible. The trick is to have some value somewhere which is declared with the type you need (return type of toast()), without actually calling toast(). You can do that by introducing another function that returns a value of appropriate type (the actual value is null), then creating a variable and assigning it the value returned by that function, then getting typeof of that.

    I could not find a way without adding unused variable, but since the variable is initialized by null that's immediately returned from the function, I suppose that runtime overhead is negligible. Here is the code:

    function toast() {
      return {
        a: "a",
        b: "b"
      }
    }
    
    function getReturnType<R> (f: (...args: any[]) => R): {returnType: R} {
        return null!;
    }
    
    // dummy variable, used for retrieving toast return type only
    let toastType = getReturnType(toast);
    
    export type ToastReturnType = typeof toastType.returnType;
    

    UPDATE Feb 2018

    In the upcoming 2.8 release, there are some new language features that make it possible without involving dummy variables and functions.

    This example compiles with typescript@next:

    export function z() {
        return {a: 1, b: '2'}
    }
    
    export function v() {
    }
    
    type ReturnType<T extends (...args: any[]) => any> = 
        T extends (...args: any[]) => infer R ? R : never;
    
    export type RZ = ReturnType<typeof z>; // { a: number; b: string; }
    export type RV = ReturnType<typeof v>; // void
    
    0 讨论(0)
提交回复
热议问题