Type or interface: typescript 到底用哪个
ChenYang Lv1

TypeInterface*都是用于描述TypeScript中对象的结构。

TypeScript分为三种类中,Any TypeBuild-In TypeUser-Defined Type

Type 与 Interface 相同点

定义TypeScriptUser-Defined Type,为函数或对象的定义契约。

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

const p1: people = {
name: 'sleepSheep',
age: 18
}

type car = {
name: string;
price: number
}

const car1: car = {
name: 'Mazada',
price: 200000
}

两者可以相互继承。interface通过extends实现继承,type通过&实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
interface people {
name: string;
}

interface student extends people {
age: number
}

const p1: student = {
name: 'sleepSheep',
age: 18
}

type transp = {
name: string;
}

type car = transp & {
price: number
}

const car1: car = {
name: 'Mazada',
price: 200000
}

不同点

  1. type 可以定义基本类型的别名 type myNumber = number;可以通过typeof定义,type myT = typeof myObj;可以申明联合类型和元组类型,type myT = exampleType1 | exampleType2; type myT = [exampleType1, exampleType2]
  2. type不能重复定义,无法声明合并,interface可以。
1
2
3
4
5
6
7
8
9
10
11
12
13
interface people {
name: string;
}

interface people {
age: number;
}
// people {name, age}
const p1: people = {
name: 'sllepSheep',
age: 25
}

参考

What is the difference between interface and type in TypeScript ?

Types vs. interfaces in TypeScript

接口介绍 - TypeScript

type和interface的区别知多少?