diff --git a/src/function.ts b/src/function.ts index 8652040..3989093 100644 --- a/src/function.ts +++ b/src/function.ts @@ -1,14 +1,21 @@ -type AnyFunc = (...arg: any) => any; +export type AnyFunc = (...args: Input[]) => Output; + +// Helper type to get the return type of a function +type ReturnTypeOf = F extends (...args: any[]) => infer R ? R : never; + +// Helper type to get the parameter types of a function +type ParametersOf = F extends (...args: infer P) => any ? P : never; type PipeArgs = F extends [ - (...args: infer A) => infer B, + infer First extends AnyFunc, + ...infer Rest extends AnyFunc[], ] - ? [...Acc, (...args: A) => B] - : F extends [(...args: infer A) => any, ...infer Tail] - ? Tail extends [(arg: infer B) => any, ...any[]] - ? PipeArgs B]> + ? Rest extends [infer Second extends AnyFunc, ...any[]] + ? ReturnTypeOf extends ParametersOf[number] + ? PipeArgs : Acc - : Acc; + : [...Acc, First] + : Acc; type LastFnReturnType, Else = never> = F extends [ ...any[], @@ -45,7 +52,10 @@ export const applyPipe = ( firstFn: FirstFn, ...fns: PipeArgs extends F ? F : PipeArgs ): LastFnReturnType> => { - return (fns as AnyFunc[]).reduce((acc, fn) => fn(acc), firstFn(arg)); + return fns.reduce( + (acc: any, fn: AnyFunc) => fn(...[acc]), + firstFn(...[arg]), + ) as LastFnReturnType>; }; /**