typescriptobjectinterfacespread-syntax

Can a TypeScript interface be spread into another interface?


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;
}

Solution

  • 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;
    }