在Typescript中,类型和接口有什么区别?

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)

所以一般来说,如果你只有一个普通的对象类型,如你的问题所示,接口通常是一种更好的方法.如果您发现自己想要编写无法编写为接口的内容,或者只想给出不同名称的内容,则类型别名更好.

  • `类型别名,但是,可以代表一些接口不能的东西.在我看来你的例子`NeatAndCool`和`JustSomeOtherName`可以创建为扩展现有`Neat`,`Cool`或`SomeType`类型的接口. (2认同)
  • 扩展两个接口并不总是产生与交集类型相同的结果,并且并非所有类型都可以扩展(而所有类型都可以别名或放入联合/交叉点) (2认同)

Dav*_*ord 5

而且,可以实现接口。

  • 这应该是评论,而不是答案。 (2认同)

ami*_*309 5

这些之间的差异也已经在这个线程中。

type Foo = {
    foo: string
};
interface Foo {
    foo: string;
}
Run Code Online (Sandbox Code Playgroud)

这里type Foointerface 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)

但是typeinterface在非常不同的上下文中使用。

let foo: Foo;
let today: Date = new Date();
Run Code Online (Sandbox Code Playgroud)

这里typefooisFootodayis Date。它就像一个变量声明,它保存了其他变量的类型信息。 type就像接口、类、函数签名、其他类型甚至值(如type mood = 'Good' | 'Bad')的超集。最后type描述了变量的可能结构或值。


小智 5

说“接口可以实现”是错误的,因为类型也可以实现

type A = { a: string };


class Test implements A {

    a: string;
}
Run Code Online (Sandbox Code Playgroud)

虽然你可以做到这一点,但你不能实现一个类型的联合,老实说这是完全合理的:)