Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using spread operator when the value is null

Is there a way to handle null in spread operator, without specifying if and else?

In following scenario, I want to spread assignedStudents only when it's not undefined.

If I do it without using if else, I get the error:

TypeError: Invalid attempt to spread non-iterable instance

To handle this, I am using if else, but thinking there is a better/elegant way of doing this.

let questions;
if (assignedStudents) {
    questions = [
        ...assignedStudents,
        {
            questionId: randomId,
            question: ''
        }
    ];
} else {
    questions = [
        {
            questionId: randomId,
            question: ''
        }
    ];
}
like image 358
Simsons Avatar asked Aug 04 '26 20:08

Simsons


1 Answers

Do you mean something like this using the nullish coalescing operator

const questions = [
  ...(assignedStudents ?? []),
  {
    questionId: randomId,
    question: ""
  }
]

Of course, this won't protect you if assignedStudents is non-iterable (like a Number or Object). It's not as fancy but if you only want to act on an array, check it with Array.isArray()

const questions = [
  ...(Array.isArray(assignedStudents) ? assignedStudents : []),
  {
    questionId: randomId,
    question: ""
  }
]

Since you've tagged this question with typescript, you should be marking assignedStudents as a nullable array, eg

assignedStudents?: Something[]

in which case the above isn't a problem any more.

like image 165
Phil Avatar answered Aug 06 '26 12:08

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!