Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 842
Lukas Bach Avatar asked Jun 22 '18 12:06

Lukas Bach


People also ask

Can a interface extend another interface TypeScript?

In TypeScript, interfaces can extend each other just like classes. This lets us copy the members of one interface to another and gives us more flexibility in how we use our interfaces. We can reuse common implementations in different places and we can extend them in different ways without repeating code for interfaces.

How can use interface inside another interface in TypeScript?

TypeScript Interface Inheritance Like JavaScript classes, an interface can inherit properties and methods from another interface using the extends keyword. Members from the inherited interface are accessible in the new interface.

How do I pass a TypeScript interface?

An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.

What TypeScript keyword allows an interface to inherit from another interface?

To inherit the interface from one to another interface, in TypeScript we can use the keyword extends that allow us to extend the set of properties and attributes from one interface to another and access it into the child interfaces accordingly.


1 Answers

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;
}
like image 73
Titian Cernicova-Dragomir Avatar answered Oct 17 '22 23:10

Titian Cernicova-Dragomir