简体   繁体   English

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

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

The following code is a common, and very neat, way of implementing wrapper functions in JavaScript.以下代码是在 JavaScript 中实现包装函数的一种常见且非常简洁的方式。

The code wraps innerFunction (which has some named arguments) with the wrapper outerFunction :代码用包装器outerFunction包装了innerFunction (它有一些命名参数):

function innerFunction(firstArgument, secondArgument, thirdArgument) {
  console.log('innerFunction', arguments);
}

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

outerFunction(1, 2, 3);

This works perfectly fine as JavaScript - you can see outerFunction passes whatever arguments to innerFunction :这在 JavaScript 中工作得非常好- 您可以看到outerFunction将任何参数传递给innerFunction

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

Typescript doesn't like this, as it wants me to put the inner functions types into the outer function. Typescript 不喜欢这样,因为它希望我将内部函数类型放入外部函数中。

Is there a better way of doing this in TypeScript?在 TypeScript 中是否有更好的方法来做到这一点? Surely TypeScript's static analysis can see the outer function gets its types from the inner function?肯定 TypeScript 的静态分析可以看到外部函数从内部函数获取其类型?

I accept the answer might be 'no, you have to add the types of the inner function to the outer function'.我接受的答案可能是“不,您必须将内部函数的类型添加到外部函数”。 But I'd like to consult with my peers here in case there's a better way of doing this.但我想在这里咨询我的同行,以防有更好的方法来做到这一点。

Typescript offers a utility type Parameters that gives you the types of the parameters of a function as a tuple. Typescript 提供了一个实用程序类型Parameters ,它以元组的形式为您提供函数参数的类型。 So you would type the outer function like the following:所以你可以像下面这样输入外部函数:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM