# 其他重要更新

WARNING

  • async 函数以及 Promise
  • tsconfig.json 支持注释
  • 动态导入表达式
  • 弱类型探测
  • ...操作符
function getIndexPromise() {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve(1)
		}, 1000)
	})
}

getIndexPromise().then((data) => {
	console.log(data, '返回数据')
})


async function asyncFn() {
	try {
		let res = await getIndexPromise()
		console.log(res, 'res')
	} catch (error) {
		console.log(error, 'error')
	}

}
asyncFn()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

使用 async 和 promise 模拟一个接口请求

interface Res {
	data: {
		[key: string]: any
	}
}

namespace axios {
	export function post(url: string, config: object): Promise<Res> {
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				let res: Res = {
					data: {}
				}
				if (url === 'login') {
					res.data.user_id = 11
				} else {
					res.data.role = 'admin'
				}
				resolve(res)
			}, 1000)
		})
	}
}

interface ParamsInfo {
	user_name: string,
	password: string
}

async function loginReq ({ user_name, password }: ParamsInfo) {
	try {
		let res = await axios.post('/login', {
			data: {
				user_name,
				password
			}
		})
		return res
	} catch (error) {
		throw new Error('报错了')
	}
}

async function getRoleReq(user_id: number) {
	try {
		let res = await axios.post('/user_roles', {
			data: {
				user_id
			}
		})
		return res
	} catch (error) {
		console.log(error, 'id-error')
		throw new Error('报错了-2')
	}
}


loginReq({
	user_name: 'nihao',
	password: '123'
}).then((res) => {
	console.log(res, 'loginReq-返回数据')
	let { data: { user_id } } = res
	getRoleReq(user_id).then(roleRes => {
		let { data: { role } } = roleRes
		console.log(role, 'role')
	})
}).catch(error => {
	console.log(error, '报错了-1')
})

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

动态导入表达式

async function getTime(format: string) {
	let moment = await import('moment')
	return moment.default().format(format)
}

getTime('L').then(res => {
	console.log(res, '时间格式') // 02/09/2022
})
1
2
3
4
5
6
7
8

弱类型探测, 可选属性就是弱类型

interface ObjIn {
	name?: string,
	age?: number
}

let objdata = {
	sex: '男'
}
function printInfoData (info: ObjIn) {
	console.log(info)
}
// printInfoData(objdata) // 报错
printInfoData(objdata as ObjIn)
1
2
3
4
5
6
7
8
9
10
11
12
13