To merge two interfaces with TypeScript, we can use extends to extend multiple interfaces. to create the IFooBar that extends IFoo and IBar . This means IFooBar has all the members from both interfaces inside.
For the purposes of this article, “declaration merging” means that the compiler merges two separate declarations declared with the same name into a single definition. This merged definition has the features of both of the original declarations.
interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastName:"Hanks", sayHi: ():string =>{return "Hi there"} } console. log("Customer Object ") console. log(customer. firstName) console.
This article explains the relation between interfaces and type aliases very well, this part is focused on small differences between them.
Both
interface IFooBar extends IFoo, IBar {}
and
type IFooBar = IFoo & IBar;
are common ways to do this and will behave identically in most cases. Since type
takes less characters to type, it could be chosen for that reason.
The inconsistency that is caused by mixed interface
and type
shouldn't be a problem; they are just suitable features to achieve the goal. If const BarClass = FooClass
does the job, class BarClass extends FooClass {}
shouldn't be preferred just because its consistently uses class
everywhere (this example is used for illustrative purposes, there's a considerable difference between these approaches).
Even though interface
and type
can behave similarly, there is a difference in case of merged interface (also covered in linked article). This will work:
interface FooBar extends IFoo, IBar {}
class FooBar { ... }
And this will cause type error:
type FooBar = IFoo & IBar;
class FooBar { ... }
If you're wanting to merge 2 interfaces which contain members more than 1 level deep:
export interface TypeOne {
one: {
two: {
hello: string;
}[]
}
}
export type TypeTwo = {
one: {
two: {
world: string;
}[]
}
} & TypeOne;
const x: TypeTwo;
x.one.two[0]. // autocompletes options are 'hello' / 'world'
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