如何在TypeScript中重用子字段

时间:2019-09-16 18:48:54

标签: typescript

我的接口定义如下:

interface One {
  one: {
    oneone: string;
    fieldA: string;
    fieldB: string;
    fieldC: string;
  }
}
interface Two {
  two: {
    twotwo: string;
    fieldA: string;
    fieldB: string;
    fieldC: string;
  }
}

如您所见,fieldAfieldBfieldC是可共享的。无论如何,我们可以分享它们吗?像

interface SharedFields {
    fieldA: string;
    fieldB: string;
    fieldC: string;
}

interface One {
  one: (extends SharedFields) {
    oneone: string;
  }
}

1 个答案:

答案 0 :(得分:3)

您可以为此使用intersection type

interface SharedFields {
    fieldA: string;
    fieldB: string;
    fieldC: string;
}

interface One {
  one: SharedFields & {
    oneone: string;
  }
}