mar*_*oop 94 javascript typescript
以下有什么区别?
type Foo = {
foo: string
};
interface Foo {
foo: string;
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*ugh 110
接口可以扩展
interface A {
x: number;
}
interface B extends A {
y: string;
}
Run Code Online (Sandbox Code Playgroud)
并且还增加了
interface C {
m: boolean;
}
// ... later ...
interface C {
n: number;
}
Run Code Online (Sandbox Code Playgroud)
但是,类型别名可以表示接口不能的某些东西
type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;
Run Code Online (Sandbox Code Playgroud)
所以一般来说,如果你只有一个普通的对象类型,如你的问题所示,接口通常是一种更好的方法.如果您发现自己想要编写无法编写为接口的内容,或者只想给出不同名称的内容,则类型别名更好.
这些之间的差异也已经在这个线程中。
type Foo = {
foo: string
};
interface Foo {
foo: string;
}
Run Code Online (Sandbox Code Playgroud)
这里type Foo
和interface Foo
看起来几乎相似,所以它令人困惑。
interface
约定以下属性(此处foo:string
)应该存在于对象中。
interface
不是class
。当语言不支持多重继承时使用它。所以interface
可以是不同类之间的公共结构。
class Bar implements Foo {
foo: string;
}
let p: Foo = { foo: 'a string' };
Run Code Online (Sandbox Code Playgroud)
但是type
和interface
在非常不同的上下文中使用。
let foo: Foo;
let today: Date = new Date();
Run Code Online (Sandbox Code Playgroud)
这里type
的foo
isFoo
和today
is Date
。它就像一个变量声明,它保存了其他变量的类型信息。
type
就像接口、类、函数签名、其他类型甚至值(如type mood = 'Good' | 'Bad'
)的超集。最后type
描述了变量的可能结构或值。
小智 5
说“接口可以实现”是错误的,因为类型也可以实现
type A = { a: string };
class Test implements A {
a: string;
}
Run Code Online (Sandbox Code Playgroud)
虽然你可以做到这一点,但你不能实现一个类型的联合,老实说这是完全合理的:)
归档时间: |
|
查看次数: |
18022 次 |
最近记录: |