Tips on setting a singular optional parameter value while invoking a function

Here is a sample function definition:

function myFunc(
  id: string,
  optionalParamOne?: number,
  optionalParamTwo?: string
) {
  console.log(optionalParamTwo);
}

If I want to call this function and only provide the id and optionalParamTwo, without needing to specify optionalParamOne, how can I achieve that?

One approach could be:

myFunc('abc', null, 'dog')

However, if there are multiple optional parameters in the function signature, providing a value for each one may not be ideal.

Check out a demo here

Answer №1

In order to provide a value for a higher-indexed parameter, you must first provide some value (even if it's undefined) for every ordered parameter.

One common approach to reduce boilerplate when invoking functions with uninteresting parameters is to use currying:

TS Playground

function myFunc (
  id: string,
  optionalParamOne?: number,
  optionalParamTwo?: string
) {
  console.log(optionalParamTwo);
}

// Define a function that expands parameters:
const myParams = (id: string, optionalParamTwo?: string) => [id, undefined, optionalParamTwo] as const;
//                                                               ^^^^^^^^^
// Include undefined for the parameters you don't want to consider when calling the function

myFunc(...myParams('abc', 'dog')); // displays "dog"

// Alternatively, curry the function:
const myFuncWithFewerParams = (
  id: string,
  optionalParamTwo?: string,
) => myFunc(id, undefined, optionalParamTwo);

myFuncWithFewerParams('abc', 'cat'); // shows "cat"

To learn more about sliced tuples in the type system for addressing partial parameters, refer to this answer.

Answer №2

To achieve the desired outcome, you can create a wrapper function without altering the original function. By introducing destructuring assignment in the wrapper function, you can pass in only the necessary parameters like this:

function myFunc(
  id: string,
  optionalParamOne?: number,
  optionalParamTwo?: string
) {
  console.log(optionalParamTwo);
}

interface MyFuncParams {
  optionalParamOne?: number,
  optionalParamTwo?: string
}

function myFuncWrapper(id: string, { optionalParamOne, optionalParamTwo }: MyFuncParams = {}) {
  myFunc(id, optionalParamOne, optionalParamTwo);
}

myFuncWrapper('abc', { optionalParamTwo: 'dog' });

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

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...

Function in Node.js/JavaScript that generates a new path by taking into account the original filepath, basepath, and desired destination path

Is there a custom function in Node.js that takes three arguments - filePath, basePath, and destPath - and returns a new path? For example: Function Signature Example var path = require('path'); // Could the `path` module in Node be useful here? ...

Is there a way to generate a modal list of values by utilizing bootstrap and angular, while incorporating spring boot as the backend technology?

I'm working on developing a generic "List of Values" feature, which will be a searchable modal containing a natural identifier and description. I have successfully built an AngularJS application in Spring Boot to accomplish this task, but unfortunatel ...

FadeOut Television static on Canvas after a period of inactivity

Is there a way to smoothly fade out the TV noise after a specific timeout period? I found this code snippet on Stack Overflow that seems to address a similar issue: var canvas = document.getElementById('canvas'), ctx = canvas.getContext( ...

Transferring a boolean model value to a JavaScript function triggers a reference to the onchange function

An onchange event is triggered in an input tag of type checkbox, calling a JavaScript function and passing three parameters from the model: <input type="checkbox" ... onchange="changeRow('@Model.Id', '@Model.Type', @Model.AwaitingAp ...

Error thrown by loader.js at line 582 of internal/modules/cjs/loader.js

Encountered this error message in the console: Error : Cannot find module. The detailed error is provided below. Any suggestions on how to resolve this? internal/modules/cjs/loader.js:582 throw err; ^ Error: Cannot find module 'C:\Users ...

If a specific class is identified, add a border to the div when clicked using JavaScript

Is there a way to use javascript/jquery to add a border to a selected div? I have multiple rows with columns, and I want only one column per row to be highlighted with a border when clicked. Each row should have one column with a border, so it's clear ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

Is it possible to load Javascript using AJAX with jQuery?

So I have this JavaScript code that I insert into a webpage using the following: <script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/sm13154955?w=640&h=395"></script> It basically places an object/embed code into the w ...

Module error caused by Typescript path inconsistency

After creating a new model named "project" within the existing project, I encountered an error when attempting to import the class into another typescript file in VS2019. The specific error message thrown is as follows: "ts2307 cannot find module ' ...

Employ various iterations of the leaflet library

Creating a web application using React and various libraries, I encountered an issue with conflicting versions of the Leaflet library. Currently, I am incorporating the Windy API for weather forecast, which utilizes Leaflet library version 1.4.0. However ...

Overabundance of Recursive Calls in Node.js Project Dependencies

After a tiring day at work, I noticed an alert for Windows SkyDrive showing that files couldn't be uploaded due to the path being too long. The lengthy directory structure made me chuckle at the technological limitation. However, it got me thinking: ...

Exploring React JS Subdomains

I have been developing a MERN application that needs to support dynamic subdomains for each company, like companyname.localhost. In order to make this work, I made an adjustment in my .env file with the line: DANGEROUSLY_DISABLE_HOST_CHECK=true After a us ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

The dimensions of the image are determined by its orientation

I am working with two different types of images on my website: vertical and horizontal. Currently, I have a JavaScript function that adjusts the height of all images to fit the screen size. However, I would like to modify this function so that it also adap ...

Exploring the process of transferring a jQuery array from a Rails controller to a PostgreSQL array column

For my project, I successfully pass a JavaScript array to a Rails controller using AJAX. The JavaScript array consists of upload image names. Within my postgresql database, there is an array column called "images." In the Rails controller, I attempted the ...

Maintain selected dropdown option after page reload

I attempted to preserve the selected item after triggering a reload with an onchange event, however, I encountered this error in the console: "TypeError: o.nodeName is undefined[Learn More]" Here is my select element : <select onchange="showMov(this. ...

The deployment on Heroku is encountering issues due to TypeScript errors related to the MUI package

As someone relatively new to TypeScript and inexperienced in managing deployments in a production setting, I've been working on a project based on this repository: https://github.com/suren-atoyan/react-pwa?ref=reactjsexample.com. Using this repo has a ...

Performing a function inside a JSON structure

I am dealing with a JSON object that contains a list of functions I need to access and run like regular functions. However, I'm struggling to figure out how to achieve this. Here is what I have attempted: Bootstrapper.dynamic = { "interaction": f ...