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

时间:2016-04-22 00:57:15

标签: javascript typescript

以下是什么区别?

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

6 个答案:

答案 0 :(得分:91)

接口可以扩展

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 :(得分:4)

此外,界面可以实现

答案 2 :(得分:2)

这些差异也已经存在于这个主题中。

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();

type foo FootodayDatetype。 它就像一个变量decleration,它保存其他变量类型的信息。 type mood = 'Good' | 'Bad'就像接口,类,函数签名,其他类型甚至值(如type)的超集。  最后<declare-styleable name="ColorPickerView"> <attr name="colors" format="reference" /> </declare-styleable> 描述了变量的可能结构或值。

答案 3 :(得分:1)

类型有点像接口,反之亦然:两者都可以由类实现。 但是有一些重要的区别: 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'
}

答案 4 :(得分:1)

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

type A = { a: string };


class Test implements A {

    a: string;
}

虽然你可以这样做,但你不能实现一个类型为Union的类型,这完全合情合理:)

答案 5 :(得分:0)

打字稿中的

type用于引用现有类型。它不能像levels那样扩展。 -mindepth 1的示例是:

interface

您可以在以下类型中使用“休息”和“传播”:

type
另一方面,

接口允许您创建新类型。

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