Concern
I am seeking a basic function that can receive a callback with either 1 or 2 arguments.
- If a callback with only 1 argument is provided, the function should automatically generate the second argument internally.
- If a callback with 2 arguments is supplied, the function should not call the second argument. It needs to be invoked within the callback instead.
Playground
Issue
TS2769: No overload matches this call.
Overload 1 of 2, '(callback: Callback): void', gave the following error.
Argument of type '(a: any, b: any) => void' is not assignable to parameter of type 'Callback'.
Overload 2 of 2, '(callback: Callback): void', gave the following error.
Argument of type '(a: any, b: any) => void' is not assignable to parameter of type 'Callback'.
Code
type B = () => void;
interface Callback {
(a: number): void;
(a: number, b: B): void;
(a: number, b?: B): void;
}
function test(callback: Callback): void;
function test(callback: Callback): void;
function test(callback: Callback): void {
const a = 1;
const b = () => console.log('hello');
if (callback.length === 1) {
callback(a);
b(); // calling "b" directly
}
if (callback.length === 2) {
callback(a, b);
}
}
// |--| ERROR
test((a, b) => {
console.log(a);
b();
});