簡體   English   中英

我可以使用擴展語法使用 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 的靜態分析可以看到外部函數從內部函數獲取其類型?

我接受的答案可能是“不,您必須將內部函數的類型添加到外部函數”。 但我想在這里咨詢我的同行,以防有更好的方法來做到這一點。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM