Typescript output type return from passed functions return type

Maybe I'm trying to achieve the impossible, but here.

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

eg.

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 heavily introduce my answers for some compile-time errors.

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

** Note: Code hit together for demonstration **

Greetings

+4
source share
1 answer

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);

Function arg , - T. T .

+4

Source: https://habr.com/ru/post/1666011/


All Articles