2016-04-22 101 views
39

以下几点有什么区别?在Typescript中,类型和接口有什么区别?

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

类型不能像接口扩展那样扩展。类型只是一个类型的别名。 – PSL

+1

Guidance at here:https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html#type-alias – basarat

+1

我主要使用外部数据的类型,例如来自JSON文件,或者如果你只写函数而不使用OOP类。 – Kokodoko

回答

58

接口可扩展

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; 

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

+2

'然而,类型别名可以表示一些接口无法接口的东西在我看来,您的示例'NeatAndCool'和'JustSomeOtherName'可以创建为扩展现有的'Neat','Cool'或'SomeType'类型的接口。 –

4

此外,接口可以实现

+0

而一个对象可以实现多个接口'类Thing implements Neat,Cool' – Kokodoko

+0

你是什么意思? Type也可以实现 – nadav

0

类型有点像接口,反之亦然:两者都可以通过一个类实现。 但有一些重要的区别: 1.当Type由类实现时,属于Type的属性必须在类内初始化,而使用Interface时必须声明它们。 2. as @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' 
} 
相关问题