繁体   English   中英

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

[英]In Typescript, what is the difference between type and interface?

以下有什么区别?

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

接口可以扩展

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;

所以一般来说,如果你只有一个普通的对象类型,如你的问题所示,接口通常是更好的方法。 如果你发现自己想写一些不能写成接口的东西,或者只想给一些东西一个不同的名字,类型别名更好。

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

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

这里的type Foointerface Foo看起来几乎相似,所以很容易混淆。

interface约定以下属性(此处为foo: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();

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

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

type A = { a: string };


class Test implements A {

    a: string;
}

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

类型有点像接口,反之亦然:两者都可以由类实现。 但是有一些重要的区别: 1. 当Type由类实现时,属于Type的属性必须在类内部初始化,而对于Interface,它们必须声明。 2. 正如@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 在打字稿中用于引用已经存在的类型 它不能像interface那样扩展。 type例子是:

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

您可以在以下类型中使用 Rest 和 Spread:

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
}

此外,还可以实现接口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM