我想创建一个函数对象(所有函数都有 1 个参数)。
并创建另一个函数,该函数可以类型安全地将来自外部调用的参数传递给对象中的一个函数。
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](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
TS playground
如何解决?
最佳答案
我们可以断言 功能[键] 接受类型为 的参数参数 以便 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
关于javascript - 类型安全从函数对象调用某些函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62198093/