'Merge Two Interfaces
Seeking confirmation or clarification
If I have two interfaces. What is the "proper" way to create a merge of those two interfaces?
IFoo {
// some stuff
}
IBar {
// some stuff
}
IFooBar extends IFoo, IBar {
// Empty
}
It works but it feels weird, like I am doing it wrong with the empty IFooBar.
Am I doing this correctly?
I also noticed that this also works:
type IFooBar = IFoo & IBar;
I have an illogical aversion to using type yet, it is much cleaner.
Solution 1:[1]
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]. // autocomplete options are 'hello' / 'world'
Solution 2:[2]
I think there it is ok, or not ok relating to what meaning of the merged interface. If IFooBar is a new entity from perspective of object-oriented design, then empty interface is all right. But if there is no such entity, but you want just merge some unrelated interfaces (for some hacky code) - then just use IFoo & IBar in variable type definition, or type for shortening this.
It's just my opinion as programmer, that came from object oriented languages like C++ and C#.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Pavel |
