TypeScript的接口可以通过扩展另一个接口来实现吗?

32
在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;
}
1个回答

56

你可以使用继承来实现:

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

3
啊..不确定为什么我没想到继承...我还忘了在TypeScript中一个接口可以继承多个接口。谢谢! - Lukas Bach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接