重用打字稿中的函数重载

时间:2020-06-15 09:13:43

标签: typescript overloading

如何在打字稿中重用函数重载?

例如,我有一些重载的功能

function apply(value: number): number;
function apply(value: string): string;

function apply(value: any): any {
    return value;
}

以及其他使用apply函数的函数

function apply2(value: number | string) {
    return apply(value); // getting 'No overloads matching this call' here
}

const result = apply2(1);

我也需要重载apply2吗?

  • 结果类型必须为数字
  • 不能使用泛型(简化示例)

1 个答案:

答案 0 :(得分:1)

原因是类型number | string既不能分配给类型number,也不能分配给string。这样,编译器就不知道您在apply2中使用了哪种重载,因此它无法告诉您apply2的返回类型是什么。

所以,是的,解决此问题的唯一方法是重载apply2函数