Last active
March 3, 2021 00:18
-
-
Save kettanaito/b0a32813bfd15e26f77a5e19e188d88c to your computer and use it in GitHub Desktop.
TypeScript snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: https://medium.com/@minaluke/typescript-compose-function-b7512a7cc012 | |
type ArityOneFn = (arg: any) => any | |
type PickLastInTuple<T extends any[]> = T extends [ | |
...rest: infer U, | |
argn: infer L | |
] | |
? L | |
: never | |
type FirstFnParameterType<T extends any[]> = Parameters<PickLastInTuple<T>>[any] | |
type LastFnParameterType<T extends any[]> = ReturnType<T[0]> | |
function compose< | |
T extends ArityOneFn[], | |
LeftReturnType extends FirstFnParameterType<T>, | |
RightReturnType extends LastFnParameterType<T> | |
>( | |
...fns: T | |
): ( | |
// Provide conditional parameter type to support left function | |
// without any arguments. | |
...args: LeftReturnType extends never ? never[] : [LeftReturnType] | |
) => RightReturnType { | |
return (...args) => { | |
return fns.reduceRight((acc: any, rightFn) => rightFn(acc), args[0]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment