I want to pass different callback functions as an argument and have them called with proper parameters.
Here is a highly simplified example of how should it work. Except that process instanceof ITwo
has no sense and I cannot find any expression that does the job.
interface IOne { (j: string): number; }
interface ITwo { (j: number): number; }
function dualArg(i: string, process: IOne | ITwo): number {
// something like this
if (process instanceof ITwo) {
// call with numeric arg
return process(i);
} else {
// conver to number
return process(+i);
}
}
function inc(i: number): number {
return ++i;
}
function idem(text: string): number {
return +text;
}
it('determine function signature', () => {
expect(dualArg('1', inc)).toBe(2);
expect(dualArg('1', idem)).toBe(1);
})
For a normal argument instanceof
will be enough for TypeScript to treat it as an object of specific type, however there does not seem to be anything similar for functions.
If I use some kind of hard-coded conditional, such as process.prototype.constructor.name === 'idem'
I get Typescript error message: Cannot invoke an expression whose type lacks a call signature. Type 'IOne | ITwo' has no compatible call signatures.
Here of course I could define process: any
to disable any TypeScript checks and the code will compile and run, but my goal is to be able to distinguish the functions just by their signature (and not rely on some other convention such as name or additional flags).