尋找一種在 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
)
我嘗試進入“函式多載”兔子洞,但這只是讓我從我開始的地方開始,基本上與意外數量的引數相同的錯誤。
uj5u.com熱心網友回復:
我認為您必須強制轉換您的方法,因為 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)
}
uj5u.com熱心網友回復:
起初我無法理解一些微妙之處,但最終打破它讓我到達那里。如果沒有首先定義謹慎的型別別名,Typescript 似乎很難消除引數型別的歧義。
我們需要使用型別謂詞根據 的值來bool確定我們是否正在處理對 BAR 類函式的呼叫。
當我們這樣做時,我們仍然沒有將型別縮小bool到具體的布林值(另一個謂詞也可以完成這項作業),但我們知道情況就是這樣,所以我們可以使用!非空斷言來允許它被傳遞給一種需要boolean.
游樂場鏈接
type FOO = (a: string, b: number) => void
type BAR = (a: number, b: string, c: boolean) => void
function isBAR(method: any, bool: boolean | undefined): method is BAR {
return typeof method === 'function' && typeof bool !== undefined
}
const foo = (a: string, b: number) => {
//do something
}
const bar = (a: number, b: string, c: boolean) => {
//do something
}
const myDynamicFunction = (
str: string,
method: FOO | BAR,
num: number,
bool?: boolean
) => {
isBAR(method, bool) ? method(num, str, bool!) : method(str, num)
}
myDynamicFunction('string', foo, 5)
myDynamicFunction('string', bar, 5, true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/491218.html
標籤:javascript 打字稿 类型
上一篇:在陣列中搜索并回傳多個結果
