Obtaining the return type of a function

前端 未结 7 2339
既然无缘
既然无缘 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:33

    EDIT

    As of TypeScript 2.8 this is officially possible with ReturnType.

    type T10 = ReturnType<() => string>;  // string
    type T11 = ReturnType<(s: string) => void>;  // void
    type T12 = ReturnType<(() => T)>;  // {}
    type T13 = ReturnType<(() => T)>;  // number[]
    

    See this pull request to Microsoft/TypeScript for details.

    TypeScript is awesome!


    Old-school hack

    Ryan's answer doesn't work anymore, unfortunately. But I have modified it with a hack which I am unreasonably happy about. Behold:

    const fnReturnType = (false as true) && fn();
    

    It works by casting false to the literal value of true, so that the type system thinks the return value is the type of the function, but when you actually run the code, it short circuits on false.

提交回复
热议问题