覆盖接口中的可选继承的嵌套属性

时间:2019-08-08 15:19:10

标签: typescript inheritance interface nested

我有以下界面:

export interface InterfaceA {
    propA?: any;
}

export interface MyBaseInterface extends InterfaceA {
    propA?: {
        nestedPropA?: {
            nestedNestedPropA: string;
            nestedNestedPropB: string;
        };
    };
};

然后我想扩展MyBaseInterface并继承我所有的道具,但添加更多,就像这样,结果如下

export interface MyNewInterface {
    propA?: {
        nestedPropA?: {
            nestedNestedPropA: string;
            nestedNestedPropB: string;
            nestedNestedPropC: string;
        };
    };
};

所以我尝试了一些基于this question的示例,例如:

export interface MyNewInterface extends MyBaseInterface {
    propA?: MyBaseInterface['propA'] & {
        nestedPropA?: MyBaseInterface['propA']['nestedPropA'] & {
            nestedNestedPropC: string;
        };
    };
};

但是它会说“ MyBaseInterface没有nestedPropA”(因为它是可选的)。如果我将道具设为非可选,它将不会覆盖它。最后,如果我做到了extends Required<>,它将迫使我进一步实施我不想要的道具。

有人可以帮我吗?谢谢

1 个答案:

答案 0 :(得分:1)

您显然已经达到了接口继承的自然界限。 Afaik Lookup types无法表达此可选​​约束,也不能对接口使用条件类型。

类型别名在类型定义和可选属性的组成方面提供了更大的灵活性:

type A = {
  // your base properties
};

type B = A & {
  propA?: {
    nestedPropA?: {
      nestedNestedPropA: string;
      nestedNestedPropB: string;
    };
  };
}

type C = B & {
  propA?: {
    nestedPropA?: {
      nestedNestedPropC: string;
    };
  };
}

注意:您无法在A中定义propA?: any;,因为在创建交集类型时,propA类型将扩展为any,并且您会松散强类型。您可以通过以下方式简单地证明这一点:

type T1 = any
type T2 = string
type T3 = T1 & T2 // type T3 = any ; any wins

这是上面示例中的TS Playground