Typescript ReturnType of generic function

前端 未结 4 600
长发绾君心
长发绾君心 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 07:10

    I found a good and easy way to achieve this if you can change the function definition. In my case, I needed to use the typescript type Parameters with a generic function, precisely I was trying Parameters> and effectively it doesn't work. So the best way to achieve this is changing the function definition by an interface function definition, this also will work with the typescript type ReturnType.

    Here an example following the case described by the OP:

    function foo(e: T): T {
       return e;
    }
    
    type fooReturn = ReturnType>; // Damn! it throws error
    
    // BUT if you try defining your function as an interface like this:
    
    interface foo{
       (e: T): T
    }
    
    type fooReturn = ReturnType> //it's number, It works!!!
    type fooParams = Parameters> //it also works!! it is [string]
    
    //and you can use the interface in this way
    const myfoo: foo = (asd: number) => {
        return asd;
    };
    
    myfoo(7);
    

提交回复
热议问题