Home > Software engineering >  ts: Type must have a Symbol.iterator when trying to push to array conditionally
ts: Type must have a Symbol.iterator when trying to push to array conditionally

Time:09-19

I'm trying to add an item conditionally into an array:

  fields: [
    ...formPayload.fields.filter((field) => field !== oldValue),
    ...(!formPayload.fields.includes(newValue) ? newValue : null), //ERROR
    
  ],

But the last line gives the following error: type string | null must have a Symbol.iterator method that returns an iterator

If I replace the last line with

...newValue

It's working. What is wrong with my syntax?

CodePudding user response:

You just need to remove the spread operator from the second line:

TS Playground

// before:
...(formPayload.fields.includes(newValue) ? newValue : null),
// after:
(formPayload.fields.includes(newValue) ? newValue : null),

And if you want no value at all instead of null, you can use this syntax:

...(formPayload.fields.includes(newValue) ? [newValue] : []),
  • Related