Search code examples
javascripttypescriptcompositionhigher-order-functionscurrying

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


I have the following function. It composes, a number of functions, from Right to Left. Just that, works like a charm. I want to use though a Generic instead of standard type(e.g: string, number etc)..

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

SO, I do not have to use it only with strings like that:

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.

How to do that? Any Ideas??I have tried multiple syntaxes, but TS complains. And cannot find a reference online. Thanks you..


Solution

  • Add a generic return type to the reducer functions:

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

    All reducers will accept an accumulator of the same type R.