patterntypescriptCritical
Merge Two Interfaces
Viewed 0 times
twointerfacesmerge
Problem
Seeking confirmation or clarification
If I have two interfaces. What is the "proper" way to create a merge of those two interfaces?
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:
I have an illogical aversion to using
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
This article explains the relation between interfaces and type aliases very well, this part is focused on small differences between them.
Both
and
are common ways to do this and will behave identically in most cases. Since
The inconsistency that is caused by mixed
Even though
And this will cause type error:
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 { ... }Code Snippets
interface IFooBar extends IFoo, IBar {}type IFooBar = IFoo & IBar;interface FooBar extends IFoo, IBar {}
class FooBar { ... }type FooBar = IFoo & IBar;
class FooBar { ... }Context
Stack Overflow Q#49723173, score: 323
Revisions (0)
No revisions yet.