Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero or all optional but typed parameters

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?

like image 963
philipp Avatar asked Dec 07 '25 11:12

philipp


1 Answers

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

like image 136
Aleksey L. Avatar answered Dec 09 '25 00:12

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!