合并两个接口 [英] Merge Two Interfaces

查看:75
本文介绍了合并两个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻求确认或澄清

如果我有两个接口.什么是适当"?创建这两个接口的合并的方法?

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
}

它有效,但感觉很奇怪,就像我用空的 IFooBar 做错了一样.

It works but it feels weird, like I am doing it wrong with the empty IFooBar.

我这样做对吗?

我也注意到这也有效:

type IFooBar = IFoo & IBar;

我对使用 type 有一种不合逻辑的反感,但它更简洁.

I have an illogical aversion to using type yet, it is much cleaner.

推荐答案

这篇文章很好的解释了接口和类型别名的关系,这一部分关注的是它们之间的细微差别.

This article explains the relation between interfaces and type aliases very well, this part is focused on small differences between them.

两者

interface IFooBar extends IFoo, IBar {}

type IFooBar = IFoo & IBar;

是执行此操作的常用方法,并且在大多数情况下表现相同.由于 type 需要较少的字符来输入,因此可以选择它.

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.

interfacetype 混合导致的不一致应该不是问题;它们只是实现目标的合适特征.如果 const BarClass = FooClass 完成这项工作,class BarClass extends FooClass {} 不应该是首选,因为它始终在任何地方使用 class(这示例仅用于说明目的,这些方法之间存在相当大的差异).

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

尽管 interfacetype 的行为相似,但合并接口的情况有所不同(也在链接文章中介绍).这将起作用:

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

这会导致类型错误:

type FooBar = IFoo & IBar;
class FooBar { ... }

这篇关于合并两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆