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

2021-10-12 18:42:46 +08:00
 shintendo

首先我有一个对象叫 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

1320 次点击
所在节点    TypeScript
2 条回复
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
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)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/807381

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX