【发布时间】:2021-06-16 03:42:40
【问题描述】:
当类型是联合类型并且类型“重叠”时,我无法理解为什么 TypeScript 会为数组元素推断某种类型。我已将其减少到最低限度:
interface Base {
id: string;
}
interface Child {
id: string;
parentId: string;
}
interface Obj {
nodes1: Base[] | Child[];
nodes2: (Base | Child)[];
}
const obj: Obj = {
nodes1: [],
nodes2: []
};
const node1 = obj.nodes1[0]; // typed as Base
const node2 = obj.nodes2[0]; // typed as Base | Child
如果我更改Base,那么它不仅仅是Child 属性的子集,如下所示:
interface Base {
baseId: string;
}
现在,node1 和 node2 都被推断为 Base | Child。这是我第一次预料到的。在我的真实代码中,数组可以是Base 类型,也可以是Child 类型,所以打字感觉更好Base[] | Child[],但我现在不得不使用(Base | Child)[]。我可以做一个更大的重构来引入泛型,但这不是一个简单的改变。
为什么类型推断为仅Base 而不是Base | Child?
【问题讨论】:
标签: typescript