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;
}
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With