【问题标题】:How to infer function return type and arguments names and types?如何推断函数返回类型和参数名称和类型?
【发布时间】:2026-02-21 15:00:01
【问题描述】:

我想在 react native 中创建一个钩子,在它的参数中我想传递一个函数和它的变量,EX:

const useHook = (functionName, functionArgs) {...}

我的问题是:我如何推断“functionName”参数类型以及它的返回类型。

这样当我编写 useHook 并传递一个函数时,intelesense 会自动向我显示函数 args 名称和类型?

我试过了,但没有用:

const useHook = <T, R>(fun: (args: T) => R, args: T) => {
  fun(args);
}

【问题讨论】:

  • 代码(functionName, functionArgs) {...} 不是有效的语法(那里应该有=&gt; 吗?)你试过的具体是什么不起作用?您是否需要多个参数或类似this 的东西? minimal reproducible example 在这里会很有帮助。
  • 谢谢@jcalz 你的例子,它工作得很好,但我想要的是,而不是传递由逗号分隔的参数,我想传递一个对象:我添加了这个: const useHook = (fun: (...args: T) => R, {...args}: T) => { return fun(...args); } 但自动补全只检测 args 类型而不是参数的名称。

标签: typescript typescript-typings


【解决方案1】:

你的函数签名足够好,你只是忘了返回结果:

const useHook = <T, R>(fun: (args: T) => R, args: T) => {
  return fun(args);
}

或缩短:

const useHook = <T, R>(fun: (args: T) => R, args: T) => fun(args);

【讨论】: