Typescript infer return type from passed functions return type

Question

I might be trying to achieve the impossible but here goes.

I want to define a function ( function A ) which will return the same type as a new function passed into the parameter of function A.

e.g.

export function test<T> ( arg:Function ):T {
    return arg;
}

function a():string {
    return 'a';
}

function b():number {
    return 0;
}

let aVal:string = test(a);
let bVal:number = test(b);

Obviously this will allow me to strongly type my responses for some compile time errors.

Does anyone have any ideas or know if I'm just dreaming.

** Note: Code slapped together for demo **

Cheers


Show source
| generics   | function   | typescript   2017-01-06 16:01 1 Answers

Answers ( 1 )

  1. 2017-01-06 17:01

    How about this?

    function test<T>(arg: () => T): T {
        return arg();
    }
    
    function a(): string {
        return 'a';
    }
    
    function b(): number {
        return 0;
    }
    
    let aVal: string = test(a);
    let bVal: number = test(b);
    

    Instead of using the Function interface we defined arg as a function that takes no arguments and returns something of type T. The actual type T then can be defined by the function that's passed in.

◀ Go back