TypeScript带来了什么?
- 类型安全
- 下一代JS特性
- 完善的工具链
TS基础——基础类型
- boolean,number,string
- 枚举enum
- any,unknown,void
- never
- 数组类型 [ ]
- 元组类型tuple
TS基础——函数类型
- 定义:TS定义函数类型时,要定义输入参数类型和输出参数类型。
- 输入参数:参数支持可选参数和默认参数。
- 输出参数:输出可以自动推断,没有返回值时,默认为void类型。
- 函数重载:名称相同但参数不同,可以通过重载支持多种类型。
function add(x: number[]):number
function add(x: string[]):string
function add(x: any[]):any {
if(typeof x[0] === 'string') {
return x.join()
}
if(typeof x[0] === 'number') {
return x.reduce((acc , cur) => acc + cur)
}
}
TS基础——interface
-
定义:接口是为了定义对象类型
-
特点:
- 可选属性:?
- 只读属性:readonly
- 可以描述函数类型
- 可以描述自定义类型
-
总结:接口非常灵活
interface Person {
name: string
age: number
}
const p1:Person = {
name: 'zhang',
age: 18
}
// p1.age = 18;
// p1.name = 'zhang';
interface RandomKey {
[propName: string] : string
}
const obj: RandomKey = {
a: 'hello',
b: 'world',
c: 'typescript',
}
TS基础——类
-
定义:写法和JS差不多,增加了一些定义
-
特点:
-
增加了public,private,protected修饰符
-
抽象类:
- 只能被继承,不能被实例化
- 作为基类,抽象方法必须被子类实现
-
interface约束类,使用implements关键字
-
class Person {
protected name: string
private sex: string
public constructor (name: string){
this.name = name
this.sex = 'male'
}
}
class Student extends Person {
study(){
console.log(this.name);
console.log(this.sex);// 私有,只能在类的内部访问
}
}
let person = new Person("daming");
person.name // 受保护,只能在子类中访问
person.sex // 私有,只能在类的内部访问
TS进阶——高级类型
- 联合类型 |
let num : number | string
num = 8
num = 'eight'
- 交叉类型 &
interface Person {
name : string
age : number
}
// 属性扩展
type Student = Person & { grade : number }
const stu : Student
stu.age
stu.grade
stu.name
- 类型断言
- 类型别名 (type VS interface)
-
定义:给类型起个别名
-
相同点:
- 都可以定义对象或函数
- 都允许继承
-
差异点:
- interface是TS用来定义对象,type是用来定义别名方便使用;
- type可以定义基本类型,interface不行;
- interface可以合并重复声明,type不行;
-
TS进阶——泛型
基本定义
-
泛型语法是 < > 里面写类型参数,一般用T表示;
-
使用时有两种方法指定类型:
- 定义要使用的类型
- 通过TS类型判断,自动推导类型
-
泛型的作用是临时占位,之后通过传来的类型进行推导;
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:将类型属性变为只读
- Pick,Record等
TS实战——声明文件
- declare:第三方库需要类型声明文件
- .d.ts:声明文件定义
- @types:第三方库TS类型包
- tsconfig.json:定义TS的配置
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 : '非常棒!'
})
- Case1:路径错误
- Case2:参数错误