如何在组合函数中传递泛型,而不是简单类型(例如:字符串、数字)

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 抱怨。并且无法在网上找到参考。谢谢你..

将通用 return 类型添加到 reducer 函数:

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

所有减速器都将接受相同类型的累加器R