湖上湖
2022-09-16 21:54:11
我想創(chuàng)建一個(gè)函數(shù)對(duì)象(所有函數(shù)都有1個(gè)參數(shù))。并創(chuàng)建另一個(gè)函數(shù),該函數(shù)可以對(duì)參數(shù)從外部調(diào)用傳遞到對(duì)象中的一個(gè)函數(shù)進(jìn)行類型保護(hù)。const double = (v: number) => v * vconst concat = (v: string) => v + vconst functions = { double, concat}const execute = <T extends keyof typeof functions> (key: T, param: Parameters<typeof functions[T]>[0]) => { functions[key](param) // here i can't match param type to function argument type, and getting an error}execute('double', 'str') // here everything is fine i get correct TypeError如何解決這個(gè)問題?
1 回答

蝴蝶刀刀
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
我們可以斷言函數(shù)[key]采用參數(shù)類型的參數(shù),以便TS確認(rèn)函數(shù)在運(yùn)行時(shí)始終獲得正確的參數(shù)類型。
const double = (v: number) => v * v
const concat = (v: string) => v + v
const functions = {
double, concat
}
const execute = <T extends keyof typeof functions>
(key: T, param: Parameters<typeof functions[T]>[0]) => {
(functions[key] as (v:typeof param)=>typeof param)(param)
}
execute('double', 5)
execute('double', 'ram) // error
execute('concat', 'ram')
execute('concat', 5) // error
添加回答
舉報(bào)
0/150
提交
取消