【发布时间】:2021-02-20 14:55:42
【问题描述】:
问题
我只想要一个接受带有 1 或 2 个参数的回调的简单函数。
- 如果只传递了 1 个参数回调,该函数将自动调用函数内部创建的不存在的第二个参数。
- 如果传递了 2 个参数回调,则不会调用该函数的第二个参数。您必须在回调中调用它。
错误
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'.
代码
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();
});
【问题讨论】:
-
因为它会在回调中抛出错误:“TS2722:无法调用可能是'未定义'的对象。”
-
为什么不总是传递两个参数呢?喜欢this。