You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并Cart接口中可能为undefined的两个ProductPromotion数组?

TypeScript合并可能为undefined的数组的简洁方案

问题场景

定义了如下TypeScript接口:

interface Cart {
    orderPromo?: ProductPromotion[],
    productPromo?: ProductPromotion[],
}

其中orderPromo和productPromo均为ProductPromotion类型数组,但存在为undefined的可能。尝试用扩展运算符合并两个数组时:

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

触发TS2488错误:

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

简洁优雅的合并方案

方案1:空值合并运算符(??)兜底空数组

使用??为可能的undefined值兜底成空数组,精准处理仅当值为null或undefined的情况:

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

方案2:利用Array.concat自动忽略undefined

Array.concat方法会自动跳过undefined参数,代码更简洁:

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

补充:逻辑或(||)兜底(慎用)

如果确定数组不会是空数组(仅可能为undefined),也可以用||,但它会把空数组也判定为假值替换,精准度不如??:

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

内容的提问来源于stack exchange,提问作者Gustavo Rey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 10:25:11