与联合类型的Typescript没有兼容的调用签名错误

时间:2018-01-26 12:40:47

标签: typescript

我有两个类,它们都有一个具有相同名称的函数,但是它们期望一个不同的参数对象:

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

然后我有一个得到C1 | C2的函数,我尝试用一​​个配置对象调用该函数,该对象具有的所有属性 C1.f和{{1 }}

但这会产生错误:

C2.f

我能想出的最佳解决方案是添加const fx = (c: C1 | C2) => { const params = { a: "a", b: "b" }; c.f(params); } 隐式投放instanceofcC1并调用函数:

C2

Typescript playground link

是否有一种更简单的方法可以在没有类型转换的情况下调用公共函数?

2 个答案:

答案 0 :(得分:0)

//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);
}

答案 1 :(得分:0)

试试这段代码:

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);
}