TypeScript合并窄类型与宽类型数组为何丢失宽类型推断信息?
类型推断结果的成因如下:
- 首先TypeScript采用结构化类型系统,
ItemExist天然是ItemNew的子类型:ItemExist包含了ItemNew要求的所有属性(text: string),因此所有ItemExist类型的值都可以被赋值给ItemNew类型的变量,二者存在明确的父子类型关系。 - TypeScript对数组扩展运算的默认类型推断逻辑是「取两个数组元素类型的公共超类型」,而非直接生成联合类型。在你的场景中
ItemNew就是ItemNew和ItemExist的公共超类型,因此合并后的数组直接被推断为ItemNew[],而不是联合类型数组。
如果需要得到Array<ItemNew | ItemExist>的类型,手动标注变量类型即可:
const items: Array<ItemNew | ItemExist> = [...itemsNew, ...itemsExist];
补充验证:如果两个数组的元素类型不存在父子继承关系,比如分别是
{a: number}和{b: string},合并后的数组就会被自动推断为联合类型数组。
内容的提问来源于stack exchange,提问作者Dartess
相关产品推荐
相关产品推荐

