Home > Net >  How to specify single optional parameter value when calling a function
How to specify single optional parameter value when calling a function

Time:03-11

I have the following function:

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

I would like to call this function by specifying the id as it is required and optionalParamTwo. I don't care about optionalParamOne. I cannot change this function.

How can I call this function with the parameters id and optionalParamTwo without having to specify optionalParamOne?

I could do this:

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

But I have many optional parameters in my function signature and I'd rather not specify a value for each.

Demo

CodePudding user response:

It's not possible to do so without changing the function. You can write a wrapper around this function with destructuring assignment like so to achieve the desired result:

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' });

CodePudding user response:

You must provide some value (even if its undefined) for every ordered parameter before you can provide a value for a higher-indexed parameter.

The common pattern for reducing boilerplate when invoking functions with uninteresting parameters is to curry:

TS Playground

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

// Create a parameter-expanding function:
const myParams = (id: string, optionalParamTwo?: string) => [id, undefined, optionalParamTwo] as const;
//                                                               ^^^^^^^^^
// Include undefined for the params you don't want to think about when calling the function

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

// Or just curry it:
const myFuncWithFewerParams = (
  id: string,
  optionalParamTwo?: string,
) => myFunc(id, undefined, optionalParamTwo);

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

For sliced tuples (addressing partial parameters) in the type system, see this answer.

  • Related