深入浅出TypeScript
1.为什么要学TS
| TypeScript | JavaScript |
|---|---|
| JavaScript的超集,用于解决大型项目的代码复杂性 | 一种脚本语言,用于创建动态网页 |
| 强类型,支持静态和动态类型 | 动态弱类型语言 |
| 可以在编译期间发现并纠正错误 | 只能在运行时发现错误 |
| 不允许改变变量的数据类型 | 变量可以被赋值成不同类型 |
特性
- 类型安全
- 下一代JS特性
- 完善的工具链
2. TS基础
- 基础类型
1.Boolean,number,string
2.枚举enum
3.any,unknown,void
4.never
5.数组类型[]
6.元组类型tuple
2.函数类型
3.interface 接口
定义:接口是为了定义对象类型
特点:
-可选属性
-只读属性:readonly
-可以描述函数类型
-可以描述自定义属性
4.类
定义:写法和JS差不多,增加了一些定义
特点:
-增加了public,private,protected等修饰符
-抽象类;
-只能被继承,不能被实例化
-作为基类,抽象方法必须被子类实现
-interface约束类,使用implements关键字
3.TS进阶
1.高级类型
-
联合类型 |
let num: number | string num = 8 num = 'eight' -
交叉类型 &
interface Person { name: string age: number } type Student= Person & { grade: number } const stu:Student stu.//age //grade //name -
类型断言
-
类型别名(type VS interface)
-定义:给类型起个别名
-相同点:
1.都可以定义函数或对象
2.都允许继承
-差异点:
1.interface是TS用来定义对象,type时用来定义别名方便使用;
2.type可以定义基本类型,interface不行;
3.interface可以合并重复声明,type不行;
---相同点
interface Person1 {
name: string
age: number
}
type Person2 = {
name: string
age: number
}
const person1:Person1 = {
name:'lin,
age: 18
}
const person2:Person2 = {
name:'lin',
age: 18
}
---不同点
1.
interface Person {
name: string
}
interface Person {
age: number
}
const person: Person = {
name :'lin',
age:18
}
2.
type Person = {//Person报错
name:string
}
type Person = {//Person报错
age: number
}
const person : Person = {
name: 'lin',
age:18//整条报错
}
-
泛型
基本定义: 1.泛型的语法是<>里面写类型参数 2.使用时有两种方法指定类型: 1.定义要使用的类型 2.通过TS类型推断,自动推导类型 !3.泛型的作用时临时占位,之后通过传来的类型进行推导; // function print<T>(arg: T): T { console.log(arg); return arg; } print<string>('hello') // 定义T为 string print('hello') //TS 类型推断,自动推导类型为string基础操作符
- typeof:获取类型
- keyof:获取所有键
- in:遍历枚举类型
- T[K]:索引访问
- extends:泛型约束
常用工具类型
- Partial: 将类型属性变为可选
- Required : 将类型属性变为必选
- Readonly : 将类型属性变为只读
4.TS实战
-
声明文件
-
declear:三方库需要类型声明文件
-
.d.ts:声明文件定义
-
@types:三方库TS类型包
-
tsconfig.json:定义TS的配置
-
-
泛型约束后端接口类型
import axios from 'axios'
interface API {
'book/detail': {
id: number,
},
'book/comment': {
id: number
comment: string
}
}
function request<T extends keyof API>(url: T,obj : API[T]){
return axios.post(url, obj)
}
request('book/comment' , {
id: 1,
comment: 'good'
})