Typesafe从函数对象中调用某些函数

问题描述 投票:3回答:1

我想创建一个函数对象(所有函数都有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

如何解决?

javascript typescript types
1个回答
0
投票

我们可以断言functions [key]接受类型为[[param的参数,以便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
© www.soinside.com 2019 - 2024. All rights reserved.