I am trying to conditionally add an object within an array of object. When I am doing it, I get a TS error in my editor saying {name: 'new', age:22} | null is not an array type
. Even if I set newAnimal
to type any
, I still get that error.
const shouldAdd = true;
const newAnimal = {
name: "new",
age: 22,
}
const data = [
{
name: "dog",
age: 11
},
...(shouldAdd ? [newAnimal] : null),
{
name: "cat",
age: 21,
}
]
CodePudding user response:
You're attempting to destructure null
as an array. You'll need to use []
instead:
const data = [
{
name: "dog",
age: 11
},
...(shouldAdd ? [newAnimal] : []),
{
name: "cat",
age: 21,
}
]