TypeScript: Is it possible to get the return type of a generic function?

前端 未结 3 356
失恋的感觉
失恋的感觉 2020-12-17 16:27

I have exported a function from some module that looks like:

export function MyFunc() {
    return {
        foo: (in: A) => void
    }
}
         


        
3条回答
  •  离开以前
    2020-12-17 16:29

    Expanding on Aidin's answer, I've managed to make ReplaceTypeIn, which works for any number of elements, objects as well as arrays, and uses only a couple of lines:

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Derived from https://stackoverflow.com/a/53808212 by jcalz (https://stackoverflow.com/users/2887218)
    export type IfEquals =
        (() => G extends T ? 1 : 2) extends
        (() => G extends U ? 1 : 2) ? Y : N;
    
    type ReplaceType = IfEquals;
    type ReplaceTypeIn = {
      [K in keyof T]: ReplaceType;
    };
    
    // ~~~~~~~~~~~~~~~~~~~~~~ SAMPLE FUNCTIONS ~~~~~~~~~~~~~~~~~~~
    
    export function MyFunc1() {
      return {
        foo: (os: T) => {}
      }
    }
    
    function MyFunc2(r: 55, p: T, x: boolean): T {
        return p;
    }
    
    // ~~~~~~~~~~~~~~~~~~~~~ FIXATIONS ~~~~~~~~~~~~~~~~~~~~
    
    // Derived from https://stackoverflow.com/a/52964723 by Titian (https://stackoverflow.com/users/125734)
    class Helper1  {
        Fixate = (...args: ReplaceTypeIn, unknown, T>) => MyFunc1(...args);
    }
    type FixatedFunc1 = Helper1['Fixate'];
    
    // -- Usage
    
    type ForNumber1 = FixatedFunc1 //  {foo: (os: number) => void;}
    type ForString1 = FixatedFunc1 //  {foo: (os: string) => void;}
    
    // ~~~~~~~~~~~~~~~~~~~
    
    class Helper2  {
        Fixate = (...args: ReplaceTypeIn, unknown, T>) => MyFunc2(...args);
    }
    type FixatedFunc2 = Helper2['Fixate'];
    
    // -- Usage
    
    type ForNumber2 = FixatedFunc2 //  (r: 55, p: number, x: boolean) => number
    type ForString2 = FixatedFunc2 //  (r: 55, p: string, x: boolean) => string
    

    Here's a playground link for the example above.

提交回复
热议问题