【问题标题】:callback with optional 2nd argument带有可选第二个参数的回调
【发布时间】:2021-02-20 14:55:42
【问题描述】:

问题

我只想要一个接受带有 1 或 2 个参数的回调的简单函数。

  1. 如果只传递了 1 个参数回调,该函数将自动调用函数内部创建的不存在的第二个参数。
  2. 如果传递了 2 个参数回调,则不会调用该函数的第二个参数。您必须在回调中调用它。

Playground


错误

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

标签: typescript overloading


【解决方案1】:

你不需要所有这些重载

type B = () => void;

interface Callback {
  (a: number, b?: B): void;
}

function test(callback: Callback): void {
    const a = 1;
    const b = () => console.log('hello');

    switch (callback.length) {
        case 1: callback(a); b(); break;
        case 2: callback(a, b); break;
    }
}

test((a, b) => {
  console.log(a);
  
  if (typeof b === "function") {
    b()
  }
});

test((a) => { console.log(a); });

Example on the TS Playground

【讨论】:

  • 您知道console.log 接受undefined 值...但尝试调用这样的函数:b(); 并抛出错误无法调用可能是“未定义”的对象。
  • 您的“console.log”值为“b”,即“() => void | undefined”(当然没有打字稿错误)但您不能调用“undefined”...我表示“b”不能是“未定义”
  • @Altaula 在第一个“回调”中添加了b() 调用
猜你喜欢
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多