TS 基础系列之type和interface

图片来源:https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1573783262,3178598711&fm=26&gp=0.jpg

[TOC]

一 前言

在ts中type和interface关键字都可用来定义数据类型,在很多开源项目中都会大量用到,那这两者到底有什么区别,使用场景有什么不同呢。下面我们仔细来探讨一下

二 正文

2.1 interface(接口)

interface表示接口,在ts中也可以用来定义数据类型,但是仅限于对象、函数、类类型

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 User {
name: string
age: number
}

// 函数类型
interface SetUser {
(name: string, age: number): void;
}

// 类类型接口
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}

// 接口实现
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}

interface定义的类型是可以继承的,并且可以多继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface Cat {
eat: string;
}

interface Dog {
pull: string;
}

// 类型继承
interface Zoom extends Cat, Dog {
play: string;
}

const zoom: Zoom = {
eat: '疯狂吃',
pull: '疯狂拉',
play: '疯狂撸'
}

2.2 type(类型别名)

ts中type表示是类型别名,即给类型起一个新的名字。type有时候和interface非常像,但是type可以用于基本类型、联合类型、元祖以及其他任何需要手写的类型

  • 基本类型

    type可以对基本类型重命名,这里不会新建一个类型,只是创建一个新名字 IString 来引用 string类型

1
2
3
4
5
// 基本类型别名
type IString = string;

const name1: IString = '张三';
const name2: string = '李四';

type

1
2
3
4
5
6
7
8
// 对象类型
type User = {
name: string
age: number
}

// 函数类型
type SetUser = (name: string, age: number) => void;

interface

1
2
3
4
5
6
7
8
9
10
// 对象类型
interface User {
name: string
age: number
}

// 函数类型
interface SetUser {
(name: string, age: number): void;
}

声明对象或函数时,使用方式都是一样的

1
2
3
4
5
6
7
8
9
10
11
12
const user: User = {
name: '张三',
age: 24
}

let setUser: SetUser;

setUser = (name: string, age: number) => {
console.log('SetUser:', name, age)
}

setUser('10', 10);
  • 类型继承(extends)

type和interface都要支持继承(extends),并且两者都可以相互继承,也就是说type可以extend interface,interface也可以extends type,仅在语法上有区别

type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 对象类型
type User = {
name: string
age: number
}

// 类型继承: 用以扩展字段
type Teacher = User & {
education: string, // 学历
}

// 声明变量
const teacher: Teacher = {
name: '张三',
age: 24,
education: '本科'
}

interface

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

// 类型继承 用以扩展字段
interface Teacher extends User {
education: string, // 学历
}

// 声明变量
const teacher: Teacher = {
name: '张三',
age: 24,
education: '本科'
}

相互继承

type extends interface

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

// type extends interface
type Teacher = User & {
education: string, // 学历
}

interface extends type

1
2
3
4
5
6
7
8
9
type User = {
name: string
age: number
}

// interface extends type
interface Teacher extends User {
education: string, // 学历
}

2.2 不同点

  • type 可以声明几杯类型别名、联合类型、元祖等类型
  • type语句中还可以使用typeof 获取实例的类型进行赋值
  • interface 能够声明合并,而type不行

总结

参考文章