[英]Inconsistency in TypeScript function overload
Consider this example:考虑这个例子:
export function fn(arg: string): void;
export function fn(arg: number): void;
export function fn(arg: any) {
console.log(arg);
}
So, fn
can be called either with a string, or a number.因此,可以使用字符串或数字调用
fn
。
fn('hello!');
fn(42);
So far, so good.到目前为止,一切都很好。 But then
fn
is executed in a different place:但随后
fn
在不同的地方执行:
function fn2(arg2: string | number) {
fn(arg2);
}
In this case TypeScript complains:在这种情况下,TypeScript 抱怨:
No overload matches this call.
没有过载匹配此调用。 Overload 1 of 2, '(arg: string): void', gave the following error.
重载 1 of 2,'(arg: string): void',出现以下错误。
Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'. Overload 2 of 2, '(arg: number): void', gave the following error. Argument of type 'string | number' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'.ts(2769)
index.tsx(3, 17): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.
index.tsx(3, 17):针对此实现的调用会成功,但重载的实现签名在外部不可见。
Can someone help me understand what's going on here?有人可以帮我了解这里发生了什么吗?
You can add another overload您可以添加另一个重载
export function fn(arg: string): void;
export function fn(arg: number): void;
export function fn(arg: any): void;
export function fn(arg: any) {
console.log(arg);
}
fn('hello!');
fn(42);
function fn2(arg2: string | number) {
fn(arg2);
}
Overloads aren't the same as Union Types.重载与联合类型不同。 Overloads define 'separate' functions while unions allow you to put different types as arguments.
重载定义“单独的”函数,而联合允许您将不同的类型放入 arguments。
// fails
function fn2(arg2: string | number) {
fn(arg2); // uses the union type
}
// works
function fn3(arg2: string | number) {
if(typeof arg2 === 'string') {
return fn(arg2); // uses string
}
return fn(arg2); // uses number
}
This means fn2
searches for a function declaration that has an argument of type string|number
while fn3
searches for either a function with type string
or a function with type number
as its first argument.这意味着
fn2
搜索 function 声明,该声明的参数类型为string|number
,而fn3
搜索类型为string
的 function 或类型为number
的 function 作为其第一个参数。
You should not use any
if you exactly know, which type you want as a function parameter.如果您确切知道您想要哪种类型作为 function 参数,则不应使用
any
。
See the documentation for Union Types请参阅联合类型的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.