
图片来源: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可以用于基本类型、联合类型、元祖以及其他任何需要手写的类型
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);
|
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 Teacher = User & { education: string, }
|
interface extends type
1 2 3 4 5 6 7 8 9
| type User = { name: string age: number }
interface Teacher extends User { education: string, }
|
2.2 不同点
- type 可以声明几杯类型别名、联合类型、元祖等类型
- type语句中还可以使用typeof 获取实例的类型进行赋值
总结
参考文章