“覆盖”派生类型

时间:2017-12-14 15:11:07

标签: typescript

假设我有以下结构:

interface Parent {
    children : Child[];
}

interface Child {
    name : string;
}

我想创建一个类似的结构,除了我希望所涉及的每个类型都有flags属性,但我不想重新定义所有类型,因为它们有很多其他属性。基本上,我想创建相当于:

interface ParentPlus {
    flags : Flag[];
    children : ChildPlus[];
}

interface ChildPlus {
    flags : Flag[];
    name : string;
}

我试着这样做:

type ChildPlus = Child & {
    flags : Flag[];
}

type ParentPlus = Parent & {
    flags : Flag[];
    children : ChildPlus[]; //required so every child will also have `flags`
}

不幸的是,属性children的类型相当混淆了编译器(有充分理由)。以下似乎正常工作:

let parent : ParentPlus;
let x = parent.children[0].flags;

但不是以下内容,标记为错误:

for (let child of parent.children) {
    let x = child.flags;
}

有更好的方法吗?

0 个答案:

没有答案
相关问题