【问题标题】:Can a TypeScript interface be spread into another interface?一个 TypeScript 接口可以扩展到另一个接口吗?
【发布时间】:2018-12-01 22:32:40
【问题描述】:

在 JavaScript 中,可以使用扩展语法将一个对象扩展为另一个对象:

const a = {one: 1, two: 2}
const b = {...a, three: 3} // = {one: 1, two: 2, three: 3}

有没有办法以这种方式将 typescript 界面传播到另一个界面?

interface IA {
  one: number;
  two: number;
}

interface IB {
  ...IA; // Does not work like this
  three: number;
}

所以结果界面IB 看起来像这样:

{
  one: number;
  two: number;
  three: number;
}

【问题讨论】:

    标签: typescript object interface spread-syntax


    【解决方案1】:

    您可以使用继承来做到这一点:

    interface IA {
        one: number;
        two: number;
    }
    interface IC {
        other: number;
        four: number;
    }
    interface IB extends IA, IC {
        three: number;
    }
    

    【讨论】:

    • 啊..不知道为什么我没有考虑过继承...我也忘记了在 TypeScript 中一个接口可以扩展多个接口。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2019-08-31
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多