39

In JavaScript, an object can be spread into another object using the spread syntax:

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

Is there a way to spread an typescript interface into another interface in such a way?

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

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

So that the resulting interface IB would look like this:

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

1 Answer 1

62

You can just use inheritance to do that :

interface IA {
    one: number;
    two: number;
}
interface IC {
    other: number;
    four: number;
}
interface IB extends IA, IC {
    three: number;
}
1
  • 3
    Ah.. Not sure why I did not thought about inheritance... I also forgot that in TypeScript an interface can extend multiple interfaces. Thanks!
    – Lukas Bach
    Commented Jun 22, 2018 at 12:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.