[英]Reuse function overloading in typescript
How to reuse function overloading in typescript?如何在 typescript 中重用 function 重载?
For example, I have some function that is overloaded例如,我有一些过载的 function
function apply(value: number): number;
function apply(value: string): string;
function apply(value: any): any {
return value;
}
And some other function that uses the apply function以及其他一些使用应用 function 的 function
function apply2(value: number | string) {
return apply(value); // getting 'No overloads matching this call' here
}
const result = apply2(1);
Do I need to overload apply2, too?我也需要重载apply2吗?
The reason is that type number | string
原因是类型
number | string
number | string
is neither assignable to type number
, nor to string
. number | string
既不能分配给类型number
,也不能分配给string
。 This way the compiler does not know which overload you're using in apply2
, and thus it cannot tell you what the return type of apply2
will be.这样编译器就不会知道你在
apply2
中使用了哪个重载,因此它不能告诉你apply2
的返回类型是什么。
So, yes, the only way to solve this is by overloading the apply2
function所以,是的,解决这个问题的唯一方法是重载
apply2
function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.