I am just about to learn some typed functional programming, so just started with an implementation of partial application - which should be type safe.
Problem: I am trying to make a function that takes a function and zero or all of its parameters as arguments.
So I started with that interface
interface Functor {
(...args: any[]) => any
}
And came to this function:
const partial = <T extends Functor>(fx: T, ...apply: Parameters<T>): Functor =>
(...args: any[]) => fx(...apply, ...args);
The Problem here is, that ...args: Parameter<T> instructs typescript to ask for all parameters, but I want allow zero up to all
Is there any way to do that?
You can define PartialParameters utility similar to builtin Parameters:
type PartialParameters<T> = T extends (...args: infer P) => any ? Partial<P> : never;
const partial = <T extends Functor>(fx: T, ...apply: PartialParameters<T>): Functor =>
(...args: any[]) => fx(...apply, ...args);
declare function foo(a: string, b: number): boolean;
partial(foo)
partial(foo, '1')
partial(foo, '1', 1)
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With