在类型脚本中,类型和接口之间的区别是什么?

以下内容之间有什么区别?

type Foo = {
foo: string
};
interface Foo {
foo: string;
}
38884 次浏览

接口可以是 延期

interface A {
x: number;
}
interface B extends A {
y: string;
}

还有 增强版

interface C {
m: boolean;
}
// ... later ...
interface C {
n: number;
}

但是,类型别名可以表示接口不能表示的一些东西

type NumOrStr = number | string;
type NeatAndCool = Neat & Cool;
type JustSomeOtherName = SomeType;

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

此外,接口可以是 实施

类型有点像接口,反之亦然: 两者都可以由类实现。 但它们之间有一些重要的区别: 1.当 Type 由类实现时,属于 Type 的属性必须在类内初始化,而使用 Interface 必须声明它们。 正如@ryan 提到的: 接口可以扩展另一个接口,而类型不能。

type Person = {
name:string;
age:number;
}


// must initialize all props - unlike interface
class Manager implements Person {
name: string = 'John';
age: number = 55;


// can add props and methods
size:string = 'm';
}


const jane : Person = {
name :'Jane',
age:46,


// cannot add more proprs or methods
//size:'s'
}

这两者之间的差异也已经存在于这个线程中。

type Foo = {
foo: string
};
interface Foo {
foo: string;
}

在这里 type Foointerface Foo看起来几乎相似,所以它的混淆。

interface是一个契约,以下属性(herfoo:string)应该存在于一个对象中。 interface不是 class。当语言不支持多重继承时使用。因此,interface可以是不同类之间的公共结构。

class Bar implements Foo {
foo: string;
}


let p: Foo = { foo: 'a string' };

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

let foo: Foo;
let today: Date = new Date();

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

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

type A = { a: string };




class Test implements A {


a: string;
}

虽然您可以这样做,但是您不能实现类型联合的类型,这完全是有意义的:)

类型是用来引用已经 现有类型。它不能像 interface那样扩展。type的例子包括:

type Money = number;
type FormElem = React.FormEvent<HTMLFormElement>;
type Person = [string, number, number];

你可以在类型中使用 REST 和 SULAD:

type Scores = [string, ...number[]];
let ganeshScore = ["Ganesh", 10, 20, 30]
let binodScore = ["Binod", 10, 20, 30, 40]

另一方面,接口允许您创建新类型。

interface Person{
name: string,
age: number,
}


Interface can be extended with extends keyword.
interface Todo{
text: string;
complete: boolean;
}


type Tags = [string, string, string]


interface TaggedTodo extends Todo{
tags: Tags
}