我可以使用扩展语法使用 TypeScript 创建包装函数,而不必指定参数和类型吗?

Can I make a wrapper function with TypeScript using spread syntax, without having to specify arguments and types?

以下代码是在 JavaScript.

中实现包装函数的一种常见且非常简洁的方法

代码用包装器 outerFunction:

包装 innerFunction(它有一些命名参数)
function innerFunction(firstArgument, secondArgument, thirdArgument) {
  console.log('innerFunction', arguments);
}

function outerFunction() {
  console.log('outerFunction', arguments);
  innerFunction(...arguments)
}

outerFunction(1, 2, 3);

这与 JavaScript 一样工作得很好 - 你可以看到 outerFunction 将任何参数传递给 innerFunction

outerFunction [Arguments] { '0': 1, '1': 2, '2': 3 }
innerFunction [Arguments] { '0': 1, '1': 2, '2': 3 }

Typescript 不喜欢这样,因为它要我将内部函数类型放入外部函数中。

在 TypeScript 中有更好的方法吗? TypeScript 的静态分析肯定可以看到外部函数从内部函数获取类型吗?

我接受答案可能是 'no, you have to add the types of the inner function to the outer function'。但我想在这里咨询我的同行,以防有更好的方法。

Typescript 提供了一个实用程序类型 Parameters,它以元组的形式为您提供函数参数的类型。所以你可以像下面这样输入外部函数:

function innerFunction(firstArgument: string, secondArgument: number, thirdArgument: boolean) {
  console.log('innerFunction', firstArgument, secondArgument, thirdArgument);
}

function outerFunction(...args: Parameters<typeof innerFunction>) {
  console.log('outerFunction', ...args);
  innerFunction(...args);
}