0

So I will do something like this often

save(...keys: string[]) {
    keys.foreach(x => // save);
}

I can call this any of these ways because of the spread operator.

save('string1', 'string2');
save(['string1', 'string2']);
save('string');

I love this behavior but what I have a case where I have an @input on a component that I want to behave the same way. sometimes I want to just give it one item, other times I want to give it an array. How could this syntax be applied? I want to be able to do something like this.

@Input() ...myClass: ClassBase[] = [];

And usages like this.

// ts
currentClass = new ClassBase();
conflictingClasses = [new ClassBase(), new ClassBase()];

// html
<my-component [myClass]="currentClass"></my-component>
<my-component [myClass]="conflictingClasses"></my-component>

How can I get this kind of behavior? We already use this component in several places but we only give it one item, I would like to not have to mass refactor to change this component to take an array of items.

thanks!

Devcon
  • 767
  • 2
  • 8
  • 23

1 Answers1

2

I can call this any of these ways because of the spread operator.

No, the premise of your question is wrong. You must call it with n number of string arguments. A string array string[] is not the same thing. This is shown below:

function save(...keys: string[]) {
    keys.forEach(x => /** save */);
}


save('string1', 'string2'); // OKAY
save('string'); // OKAY 
save(['string1', 'string2']); // ERROR !

Please as a different question instead of editing this as it will probably not get much attention after edits . PS: have fun and stay happy!

basarat
  • 261,912
  • 58
  • 460
  • 511