24 typescript
寻求确认或澄清
如果我有两个接口.什么是创建这两个接口合并的"正确"方法.
富
IFoo{
// some stuff
}
Run Code Online (Sandbox Code Playgroud)
酒吧
IBar{
// some stuff
}
Run Code Online (Sandbox Code Playgroud)
IFooBar
IFooBar extends IFoo, IBar{
// Empty
}
Run Code Online (Sandbox Code Playgroud)
它有效,但感觉很奇怪,就像我对空的IFooBar做错了.
我这样做了吗?
我也注意到这也有效:
type IFooBar = IFoo & IBar;
Run Code Online (Sandbox Code Playgroud)
我对使用type
它有一种不合逻辑的厌恶,它更清洁.
Est*_*ask 49
本文非常好地解释了接口和类型别名之间的关系,本部分重点介绍它们之间的细微差别.
都
interface IFooBar extends IFoo, IBar {}
Run Code Online (Sandbox Code Playgroud)
和
type IFooBar = IFoo & IBar;
Run Code Online (Sandbox Code Playgroud)
这是常见的方法,在大多数情况下表现相同.由于type
输入的字符较少,因此可以选择它.
由混合引起的不一致性interface
和type
不应该是一个问题; 它们只是实现目标的合适功能.如果const BarClass = FooClass
这项工作class BarClass extends FooClass {}
不应该只是因为它始终class
在任何地方使用(这个例子用于说明目的,这些方法之间存在相当大的差异).
即使interface
并且type
行为类似,但在合并界面的情况下也存在差异(链接文章也包含在内).这将有效:
interface FooBar extends IFoo, IBar {}
class FooBar { ... }
Run Code Online (Sandbox Code Playgroud)
这将导致类型错误:
type FooBar = IFoo & IBar;
class FooBar { ... }
Run Code Online (Sandbox Code Playgroud)
如果您想合并包含超过 1 级深度的成员的 2 个接口:
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'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15141 次 |
最近记录: |