Question:
How can I merge two arrays of objects that can be undefined in TypeScript?

Problem

I have this object:


interface Cart {

    orderPromo?: ProductPromotion[],

    productPromo?: ProductPromotion[],

}


Both are the same type, however, they can be undefined, so what is the best and cleanest approach to merging them?

I thought something like these:


const promotions: ProductPromotion[] = [...cart.orderPromo, ...cart.productPromo];


But it doesn't work, I'm getting this error:


TS2488: Type 'ProductPromotion[] | undefined' must have a '[Symbol.iterator]()' method that returns an iterator.


Solution

Since the properties are optional, cart.orderPromo is either an array of ProductPromotion, or undefined (as indicated by the error message). In the latter case, the use of the >spread operator ...cart.orderPromo isn't possible.


You should therefore convert the properties to empty arrays if they are undefined, typically 

with the >null coalescing operator ??:


const promotions: ProductPromotion[] = [...cart.orderPromo ?? [], ...cart.productPromo ?? []];


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers