0

I don't seam to be able to find an answer for something fairly simple regarding the spread operator on function parameters.

Assume an interface

interface Options {
   f1?: number;
   f2?: string;
   f3?: Object;
}

and function:

private handleAllOptions(...opts: Options[]) {
    if(opts && opts.length > 0) {    // opts.length  returns 1 even if no params are provided

        // ... handle options here

    }
}

Wheteher I call the function like this:

this.handleAllOptions();

or like this:

this.handleAllOptions(myOptions);

opts.length returns 1 even if no params are provided.

Can you please explain and provide a good way how to check if any params are actually in the spread?

Felix
  • 1,662
  • 2
  • 18
  • 37
  • I am not seeing that issue, https://stackblitz.com/edit/typescript-uxngfd – penleychan Dec 06 '19 at 21:41
  • Interesting. On stackblitz i see the result OK. On my tests in Chrome I get 1 each time. Very puzzling. Could it be that initially the opts params are passed (or not) via pipe ? – Felix Dec 06 '19 at 21:50
  • Can you provide the code you're using to call the function? It must be different than what you provided and is in the stackblitz link... – Jason Goemaat Dec 06 '19 at 22:17
  • Appreciate the input gentlemen. I think I figured it out. Can you please double-check the answer below and post your input/comments. I do not want to mislead any one. – Felix Dec 07 '19 at 03:04

1 Answers1

0

Little mystery solved. Posting for others to avoid the same mistake.

In my case the variable quantity of options parameters using spread is in a pipe (still just a function), something like this:

  transform(key: string, ...opts: Options[]): any {
      // --- some code ---
      this.handleAllOptions(opts);
      // etc.
  }
                         // the mistake is here:
  private handleAllOptions(...opts: Options[]) {
      // --- some code ---
  }

The mistake I made is in using the spread operator '...' in the handleAllOptions(...) function. It needs to be without it:

  private handleAllOptions(opts: Options[]) {
                         // now we can test 
                         // if our opts are empty or not
       if (opts && opts.length > 0) {
          // etc.
  }

Any comments, corrections, improvements welcome ...

Felix
  • 1,662
  • 2
  • 18
  • 37