Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

typescript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 { ... }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...