我想创建一个函数对象(所有函数都有1个参数)。并创建另一个函数,该函数可以对参数从外部调用传递到对象中的一个函数进行类型保护。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如何解决这个问题?
1 回答

蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
我们可以断言函数[key]采用参数类型的参数,以便TS确认函数在运行时始终获得正确的参数类型。
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
添加回答
举报
0/150
提交
取消