# type vs interface

# 不同点

  1. type 可以表示基本类型、元组类型、联合类型等,interface 只能表示 Object 类型

  2. type 可以用于类型映射,interface 不可以

type Keys = 'key1' | 'key2'

type T = {
  [K in Keys]: string
}

// 以下 interface 会报错
interface I {
  [K in Keys]: string
}
1
2
3
4
5
6
7
8
9
10
  1. interface 重复声明可以自动合并,type 则会报错
interface I {
  Key1: string
}
interface I {
  Key2: number
}

// 以上代码会被自动合并为
interface I {
  Key1: string
  Key2: number
}
1
2
3
4
5
6
7
8
9
10
11
12
  1. export 导出不同,inerface 支持声明并导出,而type必须先声明后导出
export default interface I {
  Key1: string
}

type T = string
export default T
1
2
3
4
5
6

# 相同点

  1. 都可以拓展

interface 通过 extends 关键字拓展 interface 或 type

interface I1 {
  Key1: string
}
interface I2 extends I1 {
  Key2: number
}

// 也可以拓展 Type
type T = {
  Key3: string
}
interface I3 extends T {
  Key4: number
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

type 通过 & 符号使用交叉类型来拓展 interface 或 type

interface I {
  Key1: string
}
type T = I & {
  Key2: number
}

type T2 = {
  Key3: string
}
type T3 = T2 & {
  Key4: number
}
1
2
3
4
5
6
7
8
9
10
11
12
13
  1. 都可以被使用 implements 实现
interface I {
  Key1: () => any
}
class C implements I {}

// 也可以
type T = {
  Key2: () => any
}
class C implements T {}
1
2
3
4
5
6
7
8
9
10
最后更新时间: 7/22/2021, 8:39:29 PM