1

I have tried the answer of Pacerier from the question Skip arguments in a JavaScript function. But it does not seem to work.

I have a function with many arguments

this.service.list("all",null, null, localStorage.getItem('currentProgram'), null, 100, ...Array(2), environment.liveMode).subscribe(...)

The only way I've found is to write it one by one, like (,null, null or undefined,undefined).

I also set a test method to see if it was different, but it does not work as well.

test(a: any, b: any, c: any, d: string) {
    console.log(d)
}

ngOnInit() {
    this.test(...Array(3), "a")
}

I also tried other syntax proposed in the answer.

Is there a less verbose way to do this in TypeScript ?

crg
  • 4,284
  • 2
  • 29
  • 57
  • Your function has a lot of optional arguments, this could be seen as a code smell. If you can refactor the function then you should take an object instead of multiple arguments like `function foo(options: {a?: string, b?: number})`. – serrulien Nov 11 '21 at 01:16

1 Answers1

2

In TypeScript if you want to skip a parameter you're obliged to explicitly pass undefined or null as the parameter value. Example:

function f(param1?: string, param2?: number, param3?: boolean) {
// do something
}

f(,,true); // ❌ Error
f(...[,,], true); // ❌ Error
f(...Array(2), true); // ❌ Error
f(undefined, undefined, true); // ✅ Works 
f(null, null, true); // ✅ Works

You can find more information and examples in this section of the TypeScript documentation: https://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters

Tonnio
  • 574
  • 2
  • 9