类型安全从函数的对象调用某些函数

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


如何解决这个问题?


湖上湖
浏览 111回答 1
1回答

蝴蝶刀刀

我们可以断言函数[key]采用参数类型的参数,以便TS确认函数在运行时始终获得正确的参数类型。const double = (v: number) => v * vconst concat = (v: string) => v + vconst functions = {&nbsp; &nbsp; double, concat}const execute = <T extends keyof typeof functions>&nbsp; &nbsp; (key: T, param: Parameters<typeof functions[T]>[0]) => {&nbsp; &nbsp; (functions[key] as (v:typeof param)=>typeof param)(param)}&nbsp;execute('double', 5)execute('double', 'ram) // errorexecute('concat', 'ram')execute('concat', 5) // error
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript