寻找一种在 TypeScript 中定义函数的方法,该函数将接受可能具有不同签名的函数作为其参数之一
const foo = (a: string, b: number) => {
//do something
}
const bar = (a: number, b: string, c: boolean) => {
//do something
}
const myDynamicFunction = (
str: string,
// I tried this, but no dice
method: ((a: string, b: number) => void) | ((a: number, b: string, c: boolean) => void),
num: number,
bool?: boolean
) => {
if (bool) {
method(num, str, bool)
} else {
method(str, num)
}
}
myDynamicFunction(
'string', foo, 5
)
myDynamicFunction(
'string', bar, 5, true
)
我尝试进入“函数重载”兔子洞,但这只是让我从我开始的地方开始,基本上与意外数量的参数相同的错误。
我认为您必须强制转换您的方法,因为 TypeScript 无法解决这个问题:
if (bool) {
(method as (a: number, b: string, c: boolean) => void)(num, str, bool)
} else {
(method as (a: number, b: string) => void)(num, str)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句