Use Generics to get a typed result of my little compose function
My compose function is actually very simple:
const compose = (outer: any, inner: any) => (...innerParams: any) => outer(inner(...innerParams));
When I now do this:
const theInner = (p1: string, p2: string): string => [p1, p2].join(' '); const theOuter = (p1: string): number => p1.length; const theComposed = compose(theOuter, theInner); const theResult = theComposed('asdf', 'asdf');
VSCode’s type hint shows me
const theComposed: (...innerArgs: any) => any when I hover on
theComposed and on
theResult I get
const theResult: any.
So all the types are lost.
I’ve been trying out several ways to get this done with Generics, but unfortunately I seem to be unable to wrap my head around this.
This is one of my failures:
export const compose = < T extends CallableFunction, U extends CallableFunction, PT extends ThisParameterType<U> >( outer: T, inner: U ) => (...args: PT) => outer(inner(args));
And this results in
const theComposed: (...args: unknown) => any and
theResult is still any.
And the most things I tried for the return type were anyway only driving the typescript compiler going mad at me.
The desired result would be that I get:
const theComposed: (p1: string, p2: string) => number
Is that even doable?