【问题标题】:Typescript no compatible call signatures error with union typesTypescript no compatible call signatures error with union types
【发布时间】:2018-07-05 19:20:30
【问题描述】:

我有 2 个类,它们都有一个同名的函数,但它们期望不同的参数对象:

class C1 {
    public f: (params: { a: string }) => {
    }
}
class C2 {
    public f: (params: { b: string }) => {
    }
}

然后我有一个获取C1 | C2 的函数,我尝试使用一个配置对象调用该函数,该对象具有两者 C1.fC2.f 的所有属性。

但这会报错:

const fx = (c: C1 | C2) => {
    const params = { a: "a", b: "b" };
    c.f(params);
}

我能想到的最佳解决方案是添加一个instanceof 以将c 隐式转换为C1C2 并调用该函数:

if (c instanceof C1) {
    c.f(params);
} else {
    c.f(params);
}

Typescript playground link

有没有更简单的方法来调用通用函数而不需要类型转换?

【问题讨论】:

  • 如果类 C1 和 C2 是你自己的类,你可以用 f 方法指定一个接口。

标签: typescript


【解决方案1】:
//Ensure that when f is called, the params must have both `a` and `b`:
interface IC {
    f: (params: { a: string } & { b: string }) => {};
};
//Here it is fine to assume that the params contain a:
class C1 implements IC {
    public f: (params: { a: string }) => {
    }
}
//Here it is fine to assume that the params contain `b`:
class C2 implements IC {
    public f: (params: { b: string }) => {
    }
}
const fx = (c: IC) => {
    const params = { a: "a", b: "b" };
    c.f(params);
}

【讨论】:

  • 看起来不错,在严格模式下编译并在缺少任何属性时发出警告。谢谢!
  • 刚刚进行了编辑以使用& 而不是|。否则,当您尝试在函数中使用参数时,您无法确定 ab 是否存在。
  • 是的,我正在输入一条评论,当您进行编辑时它不起作用:)
【解决方案2】:

试试这个代码:

const fx = (c: C1 | C2) => {
    const params = { a: "a", b: "b" };
    type T = (params: { a: string; b: string; }) => void;
    let f_: T = c.f;
    f_(params);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 2017-03-29
    • 2022-01-19
    • 2022-12-01
    • 2023-01-27
    • 1970-01-01
    • 2015-12-06
    相关资源
    最近更新 更多