-1

In Java, we can do something like :

void myFunction(int... ints) {
   // ints will be int[], that will never be null
}

// both call method will works :
myFunction();
myFunction(0, 1, 5);

But, in angular:

myFunction(obj?: MyObj[]) {
   // obj will be an array that can be null
   // obj will by typed as "MyObj[] | undefined"
}

myFunction(); // this works
myFunction(obj1, obj2); // error

But the "obj" variable can be null. Without the ? it's not possible to run the first function.

How can I do to have an argument with unknown amount of item, but never null?

9
  • You can use spread operator to make any amount of parameters myFunction(...obj: MyObj[]). Here obj will be an array of arrays. that is what you need, if i understood you correctly Commented Oct 13, 2021 at 12:25
  • I don't need array of array, just one simple array with unknow amount of item in it Commented Oct 13, 2021 at 12:27
  • But what you tell seems what I was looking for. I through it will create like string[][] but no Commented Oct 13, 2021 at 12:29
  • I mean, in your example obj is an array of MyObj. I gave you a solutuion to push any number of expected for this function parameters in an obj array in your function Commented Oct 13, 2021 at 12:30
  • Also relevant: JavaScript variable number of arguments to function | open-ended function arguments with TypeScript Commented Oct 13, 2021 at 12:43

1 Answer 1

0

You can use spread operator to make any amount of parameters myFunction(...obj: MyObj[]). Here obj:Array<MyObj[]> will be an array of your MyObj arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

This is not spread (and it's not an operator), this is rest parameters syntax

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.