TypeScript 中,interface 和 type 的区别

interface是接口,type是类型,本身就是两个概念。只是碰巧表现上比较相似。希望定义一个变量类型,就用type,如果希望是能够继承并约束的,就 用interface。如果你不知道该用哪个,说明你只是想定义一个类型而非接口,所以应该用type。

TypeScript 中,interfacetype 主要用于类型的声明,它们的相同点以及区别如下:


相同点

都可以描述一个对象或者函数

1
2
3
4
5
6
7
8
9
/* interface */
interface User {
name: string
age: number
}

interface SetUser {
(name: string, age: number): string
}
1
2
3
4
5
6
7
8
9
/* type */
type User = {
name: string
age: number
}

type SetUser = {
(name: string, age: number): string
}

都可以进行拓展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* interface */
interface User {
name: string
age: number
}

interface ProUser extends User {
email: string
}

type VipUserType = {
readonly vip: boolean
}

/* interface 和 type 拓展*/
interface VipUserInterfce extends VipUserType {
member: boolean
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* type */
type User = {
name: string
age: number
}

type ProUser = User & {
email: string
}

interface VipUserInterface {
readonly vip: boolean
}

/* type 与 interface 拓展 */
type VipUserType = VipUserInterface & {
member: boolean
}

区别

type 可以声明基本类型别名,联合类型,元组类型,而 interface 不可以

1
2
3
4
5
6
7
8
9
10
11
/* 基本类型 */
type Name = string

/* 联合类型 */
interface Dog {}
interface Cat {}

type Pet = Dog | Cat

/* 元组类型 */
type PetList = [Dog, Cat]

interface 可以进行类型合并,而 type 不可以

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
interface Cloner {
clone(animal: Animal): Animal
}

interface Cloner {
clone(animal: Sheep): Sheep
}

interface Cloner {
clone(animal: Dog): Dog
clone(animal: Cat): Cat
}

// 以上三个 interface 会被合并成一个声明
interface Cloner {
clone(animal: Dog): Dog
clone(animal: Cat): Cat
clone(animal: Sheep): Sheep
clone(animal: Animal): Animal
}

关于 declaration-merging

本文结束感谢您的阅读

本文标题:TypeScript 中,interface 和 type 的区别

文章作者:陈宇(cosyer)

发布时间:2020年05月18日 - 10:05

最后更新:2020年11月13日 - 08:11

原始链接:http://mydearest.cn/2020/TypeScript%20%E4%B8%AD%EF%BC%8Cinterface%20%E5%92%8C%20type%20%E7%9A%84%E5%8C%BA%E5%88%AB.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!