I have a function that I can call it like this:

var a=myFunction(callback(return 33))       // a should be of type {a}
var b=myFunction(callback(return 'string')) // b should be of {type b}
var c=myFunction(callback(return [33]))     // c should be of type {number[]}

I want that a and b will be number or string or whatever based on the parameter that returns from the callback.

myFunction is calling the callback to do some calculation and returning the same type of value.

How to create the type definition for the myFunction?

1

There are 1 best solutions below

0
On
const myFunction = <T>(callback: (...args: T[]) => T): T => {
    return callback();
};

const fnclbnum = (v: number): number => v * 2;
const fnclbstr = (v: string): string => v +'test';
const fnclbstrarr = (v: string[]): string[] => [...v, 'test'];

const a: number = myFunction<number>((val) => fnclbnum(val));
const b: string = myFunction<string>((val) => fnclbstr(val));
const c: string[] = myFunction<string[]>((val) => fnclbstrarr(val));

const d: number = myFunction<number>(() => fnclbnum(2));
const e: string = myFunction<string>(() => fnclbstr("test"));
const f: string[] = myFunction<string[]>(() => fnclbstrarr(["1", "ER"]));

console.log({ d }, { e }, { f });

enter image description here