簡體   English   中英

如何在組合函數中傳遞泛型,而不是簡單類型(例如:字符串、數字)

[英]How to pass a Generic in a composition Function, instead of a simple type(e.g: string, number)

我有以下功能。 它由許多功能組成,從右到左。 就是這樣,就像一個魅力。 我想使用泛型而不是標准類型(例如:字符串、數字等)。

// I want instead of string, to use a Generic <R>, for example.
const composeUtility = (...functions: Function[]) => (initialValue: string) =>
  functions.reduceRight((accumulator, currentFn: Function) => currentFn(accumulator), initialValue);

所以,我不必只對這樣的字符串使用它:

const withComposition = composeUtility(repeatFn, exclaimFn, screamFn);
console.log(withComposition('I Love TS - So Much')); // This only accepts strings. I want to pass more than that.

怎么做? 任何想法??我嘗試了多種語法,但 TS 抱怨。 而且網上也找不到參考。 謝謝..

向 reducer 函數添加通用返回類型:

const composeUtility = <R>(...functions: ((acc: R) => R)[]) => (initialValue: R) =>
    functions.reduceRight((accumulator, currentFn: (acc: R) => R) => currentFn(accumulator), initialValue);

所有減速器都將接受相同類型的累加器R

暫無
暫無

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

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