Typescript ReturnType of generic function

前端 未结 4 598
长发绾君心
长发绾君心 2020-11-29 06:41

The new ReturnType in TypeScript 2.8 is a really useful feature that lets you extract the return type of a particular function.

function foo(e:          


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 06:45

    TypeScript compiler does not see typeof foo as generic type. I'd say it's a bug in the compiler.

    However, TypeScript has callable interfaces which can be generic without any problems, so if you introduce a callable interface compatible with the signature of your function, you can implement your own equivalent of ReturnType like this:

    function foo(x: T): T {
      return x;
    }
    
    
    interface Callable {
      (...args: any[]): R;
    }
    
    type GenericReturnType = X extends Callable ? R : never;
    
    type N = GenericReturnType; // number
    

提交回复
热议问题