类型和类
- 类型是对所有数据的分类:null undefined number string symbol bigint boolean object
- 类是对事物的抽象
typescript的好处
- 编写代码边做类型检查,减少bug
- 更智能的代码提示
函数类型声明
// 方式1
const add1 = (a: number, b: number):number => a + b
// 方式2
const add2: (a: number, b: number) => number = (a + b) => a + b
// 方式3
type Add = (a: number, b: number) => number
const add3: Add = (a,b) => a + b
// 方式4. 函数有属性,只能用interface
interface AddWithProps {
(a: number, b: number) => number
xxx: string
}
const add2:AddWithProps = (a, b) => a + b
add2.xxx = 'yyy'
TypeScrpt中其他类型
// any 永远不知道类型
let a: any = 'hi'
a.name
// unknown 开始不知道类型,使用时要确定类型
let b: unknown = JSON.parse('{"name": "xxx"}')
type C = {name: string}
type E = {age: number}
console.log((b as C).name) // 使用断言确定类型
console.log((b as E).age) // 且可以多次修改类型
// void 表示函数没有返回值
let print: () => void = function() {
console.log(1)
}
// never 表示没有类型(空集)(此时一定是出错了)
type X = number & string // never
type Y = (1|2|3) & (2|3|4) // 2|3
// tuple 表示固定长度的数组
let p: [number, string] = [100, 'x']
let p2: [number, string, boolean] = [100, 'x', true]
// 联合类型和类型区分
type A = {
name: 'a';
age; number
}
type B = {
name: 'b';
gender: string
}
const f = (n: A | B) => {
if (n.name === 'a'){
console.log(n.age)
} else {
console.log(n.gender)
}
}
// 交叉类型: 联合类型相交取交集,对象相交则合并
type A = {name: string} & {age: number}
const a: A = {
name: 'xxx',
age: 18
}
泛型
// 泛型 = 广泛的类型
type Add<T> = (a:T, b:T) => T
// type AddNumber = Add<number>
// type AddString = Add<string>
const addN: Add<number> = (a, b) => a + b
const addS: Add<string> = (a, b) => a + ' ' + b
函数重载
为同一个函数提供多个函数类型定义来进行函数重载
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
if (typeof a === 'number' && typeof b === 'number') {
return a + b
} else {
return a + ' ' + b
}
}
用泛型封装网络请求
type User = {
id: string | number;
name: string;
age: number;
}
type Response<T> = {
data: T
}
type T = Partial<Omit<User, 'id'>>
type CreateResource = (path: string) => {
create: (attrs: Omit<Partial<User>, 'id'>) => Promise<Response<User>>;
delete: (id: User['id']) => Promise<Response<never>>;
update: (id: User['id'], attrs: Omit<Partial<User>, 'id'>) => Promise<Response<User>>;
get: (id: User['id']) => Promise<Response<User>>;
getPage: (page: number) => Promise<Response<User[]>>
}
const createResource: CreateResource = (path) => {
return {
create(attrs){
const url = path + 's'
return axios.post<User>(url, {data: attrs})
},
delete(){},
update(){},
get(){},
getPage(){}
}
}
var userResource = createResource('/api/v1/user')