Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety.

Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its parameters as arguments.

Here is the initial interface:

interface Functor {
  (...args: any[]) => any
}

This led me to develop the following function:

const partial = <T extends Functor>(fx: T, ...apply: Parameters<T>): Functor =>
  (...args: any[]) => fx(...apply, ...args);

The dilemma lies in ...args: Parameter<T>, which prompts typescript to expect all parameters whereas I want to allow zero up to all.

Is there a workaround for this particular issue?

Answer №1

To create a utility called PartialParameters that works similar to the built-in 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)

Interactive Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for deleting a specific choice with Angular

Having recently started working with Angular2 / TS / ES6, I am struggling to find a solution to my issue. I have a select element with dynamically rendered options using ngFor from an array. These options are meant for selecting attributes for a product. ...

Searching for evenly distributed GPS coordinates across an area

I have a collection of data points representing mountain peaks in the European Alps that I would like to showcase on a map. To prevent cluttering the user interface, I currently retrieve the highest peaks within the visible area of the map by sorting them ...

Exploring Objects using Typescript

I need help creating a mapper for objects that allows TypeScript to recognize the returned type correctly. For example: type ExampleObject = { text: string; // this object may have properties of any type number: number; }; const object: ExampleObjec ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Issues with Typegoose and Mongoose Enums when utilizing an array of strings

One of my enums is defined as follows: export enum Careers { WEB_DEVELOPMENT = 'Web Development', MOBILE_DEVELOPMENT = 'Mobile Development', UI_UX = 'UI/UX' } This particular enum is used as a mongoose property like so: ...

Nuxt3 - TS2339: The 'replaceAll' property is not found on the 'string | string[]' type in Nuxt3

Hey there! I've been experimenting with the replaceAll() method within my Nuxt3 project and encountered a strange error. Folder Structure ───pages │ └───Work │ │ index.vue │ │ [Work].vue Template <templat ...

Update the data and paginator status

In my development project, I have implemented PrimeNG Turbotable with the code <p-table #dt. Based on information from here, using dt.reset() will clear the sort, filter, and paginator settings. However, I am looking for a solution to only reset the pa ...

Creating a velocity gauge style graph in Angular 4: A step-by-step guide

Hello, I'm currently working on building a speedtest-inspired application. While everything else is going smoothly, I'm struggling to incorporate a speedometer-like chart in Angular 2/4. Despite searching extensively, I've only come across J ...

When incorporating leaflet-routing-machine with Angular 7, Nominatim seems to be inaccessible

Greetings! As a first-time user of the Leafletjs library with Angular 7 (TypeScript), I encountered an error while using Leaflet routing machine. Here is the code snippet that caused the issue. Any ideas on how to resolve this problem? component.ts : L. ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

Exploring Angular 10's advanced forms: delving into three levels of nested form groups combined with

Project Link: Click here to view the project In my testForm, I have 3 levels of formGroup, with the last formGroup being an array of formGroups. I am trying to enable the price field when a checkbox is clicked. I am unsure how to access the price contro ...

Typescript void negation: requiring functions to not return void

How can I ensure a function always returns a value in TypeScript? Due to the fact that void is a subtype of any, I haven't been able to find any generics that successfully exclude void from any. My current workaround looks like this: type NotVoid ...

How can I effectively test the success of a form submission in next.js using jest for unit testing?

At the moment, I am in the process of developing a unit test for a registration form within my application. The main objective of this test is to ensure that the registration process can be executed successfully without actually saving any new data into th ...

Transforming query language from jQuery to Pure JavaScript

I have the following jQuery code that I am attempting to remove and convert into standard JavaScript: $('.switch').click(()=>{ $([".light [class*='-light']", ".dark [class*='-dark']"]).each((i,ele)=& ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

Converting Objects to Arrays with Angular Observables

After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perfor ...

Determining the best application of guards vs middlewares in NestJs

In my pursuit to develop a NestJs application, I aim to implement a middleware that validates the token in the request object and an authentication guard that verifies the user within the token payload. Separating these components allows for a more organi ...

Is there a way to denote a specific part of a generic type without explicitly specifying the parts as generics themselves?

My dilemma involves an object defined by a type from a 3rd party library: // Unable to modify this - it belongs to the 3rd party library; interface TypedEvent< TArgsArray extends Array<any> = any, TArgsObject = any > extends Event { args ...

Guide on the correct way to develop a Typescript NPM package accompanied by declarations?

It feels like I'm struggling with a simple task that is driving me crazy. I have several TypeScript files with code that I want to export for an npm package. In order to enable auto-imports from npm packages, all function and constant types need to b ...

Utilizing Redux with React class components: A comprehensive guide

I have been attempting to integrate Redux with React Class using TypeScript, following the guidelines provided in this tutorial. However, I am encountering numerous compilation errors and feeling overwhelmed as to where to begin troubleshooting. It is cl ...