gpt4 book ai didi

typescript - 如何让函数传递具有相同重载的参数?

转载 作者:行者123 更新时间:2023-12-04 11:44:22 28 4
gpt4 key购买 nike

我正在尝试创建一个函数,将它的参数传递给另一个函数。这两个函数都需要具有相同的重载。

function original (a: number): boolean;
function original (a: string, b: string): boolean;
function original (a: number | string, b?: string): boolean {
return true;
}

function pass (a: number): boolean;
function pass (a: string, b: string): boolean;
function pass (a: number | string, b?: string): boolean {
return original(a, b);
}
这不起作用。

Argument of type 'string | number' is not assignable to parameter of type 'string'.


Type 'number' is not assignable to type 'string'.(2345)input.tsx(4, 10): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.


Playground

最佳答案

转换到任何;)

function pass (a: number | string, b?: string): boolean {
return original(a as any, b);

// or if you have strictNullChecks: true - then b should also be casted.
return original(a as any, b as any);
}
或者使用命名元组作为参数(效果类似于重载)。
function original(...args: [a: string, b: string] | [a: number]): boolean {
return true;
}

function pass (...args: [a: string, b: string] | [a: number]): boolean {
return original(...args);
}

关于typescript - 如何让函数传递具有相同重载的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65110771/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com