Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript infer return type from passed functions return type

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

like image 595
Jon Whitefield Avatar asked Jan 06 '17 15:01

Jon Whitefield


1 Answers

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.

like image 197
toskv Avatar answered Sep 22 '22 13:09

toskv