V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
shintendo
V2EX  ›  TypeScript

Typescript 里面,如何实现这样一个函数

  •  1
     
  •   shintendo · 2021-10-12 18:42:46 +08:00 · 1299 次点击
    这是一个创建于 919 天前的主题,其中的信息可能已经有所发展或是发生改变。

    首先我有一个对象叫 tools,tools 里面是很多的工具函数,函数签名各不相同。

    然后我需要写一个函数 useTool, 大致如下:

    const useTool = (name, ...args) => {
      console.log('using tool ' + name);
      tools[name](...args);
    }
    

    请问,这个函数如果用 TS 写,应该怎样标注类型?

    我试过类似这样

    useTool(name: keyof typeof tools, ...args: Parameters<typeof tools[name]>)
    

    不能通过编译,说第二个 name 的类型是 any

    2 条回复    2021-10-12 20:22:28 +08:00
    wheelg
        1
    wheelg  
       2021-10-12 18:58:04 +08:00
    用范型试试:

    const useTool: <T extends keyof typeof tools>(
    name: T,
    ...args: Parameters<typeof tools[T]>
    ) => unknown = () => {};
    noe132
        2
    noe132  
       2021-10-12 20:22:28 +08:00
    const tool = {
    a: (p: string) => '1',
    b: (p: number) => 1,
    c: (a: string, p: number, c: boolean) => true,
    }

    type Tool = typeof tool

    const useTool = <K extends keyof Tool>(key: K, ...args: Parameters<Tool[K]>): ReturnType<Tool[K]> => {
    return (tool[key] as any)(...args)
    }

    const a: string = useTool('a', '1')
    const b: number = useTool('b', 1)
    const c: boolean = useTool('c', '1', 2, true)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1294 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:36 · PVG 07:36 · LAX 16:36 · JFK 19:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.