shintendo

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

  •  1
     
  •   shintendo · Oct 12, 2021 · 1942 views
    This topic created in 1676 days ago, the information mentioned may be changed or developed.

    首先我有一个对象叫 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 replies    2021-10-12 20:22:28 +08:00
    wheelg
        1
    wheelg  
       Oct 12, 2021
    用范型试试:

    const useTool: <T extends keyof typeof tools>(
    name: T,
    ...args: Parameters<typeof tools[T]>
    ) => unknown = () => {};
    noe132
        2
    noe132  
       Oct 12, 2021
    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)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2893 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 12:03 · PVG 20:03 · LAX 05:03 · JFK 08:03
    ♥ Do have faith in what you're doing.