Lukas Bach
Lukas Bach

Reputation: 3909

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

Upvotes: 40

Views: 21378

Answers (2)

TriThomas
TriThomas

Reputation: 413

Or ( less conventionally ).

You can use a type with a intersection:

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

type IB = {
  three: number;
} & IA;

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249686

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

Upvotes: 65

Related Questions