为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

湖上湖 2022-09-16 21:54:11
我想创建一个函数对象(所有函数都有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


查看完整回答
反对 回复 2022-09-16
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号