1、泛型->动态类型
function fn1(a: number, b: number): Array<number> {
return [a, b]
}
function fn1(a: string, b: string): Array<string> {
return [a, b]
}
2、定义函数,(动态类型)不明确类型,可以使用泛型
// 使用泛型优化: 函数名后面跟上<泛型名称> ,一般定义为T(意为type),再把类型赋值给参数
function fn<T>(a: T, b: T): Array<T> { // 返回的类型也为T
return [a, b]
}
// 推断为number
fn(1, 2) // (简写)function fn<number>(a: number, b: number): number[] (+1 overload)
fn<number>(1, 2) // (全称)
fn(true, false) // function fn<boolean>(a: boolean, b: boolean): boolean[] (+1 overload)
3、除了函数,interface和type都可以使用泛型,泛型个数随意
type C<T, Y> = string | number | T | Y
let cc1: C<boolean, null> = true
let cc2: C<boolean, null> = 'true'
let cc3: C<boolean, null> = 1
let cc4: C<boolean, null> = null
interface Inter<T> {
msg: T
}
let inter1: Inter<string> = {
msg: 'interface使用泛型'
}
let inter2: Inter<number> = {
msg: 0
}
4、其他泛型用法
// *1、泛型支持多个,返回值类型为联合类型
function add<T, Y>(a: T, b: Y): Array<T | Y> {
return [a, b]
}
add(false, 23) // function add<boolean, number>(a: boolean, b: number): (number | boolean)[]
// *2、泛型也有默认值
function add1<T = number, Y = number>(a: T, b: Y): Array<T | Y> {
return [a, b]
}
// add1() // 什么都不传,推断为number function add1<number, number>(a: number, b: number): number[]
add1(77, undefined) // 有参,根据参数的类型来判断 function add1<number, undefined>(a: number, b: undefined): (number | undefined)[]
5、实际应用 调接口的地方
泛型.ts
// * XMLHttpRequest不能使用node环境 需要编译为js文件(使用tsc命令)
const axios = {
// Promise可以接收泛型
get<T>(url: string): Promise<T> { // return的是Promise,所以接收的是Promise
return new Promise((resolve, reject) => {
let xhr: XMLHttpRequest = new XMLHttpRequest() // 调接口
xhr.open('GET', url) // 发起请求
xhr.onreadystatechange = () => { // 监听状态变化onreadystatechange
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功 xhr.responseText是字符串,要转为对象,所以用JSON.parse
resolve(JSON.parse(xhr.responseText))
}
}
xhr.send(null) // 这个必须写,不然请求无效(无参数,写null)
})
}
}
interface Data {
message: string,
code: number
}
// axios.get('./data.json').then(res => { // 推断(parameter) res: unknown
// // unknown不可以使用.操作
// res. // 无法推断
// })
axios.get<Data>('./data.json').then(res => {
console.log('进行请求了~', res); // 可推断
})
data.json
{
"message":"成功",
"code":200
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TS学习</title>
</head>
<body>
<div id="app"></div>
<script src="./泛型.js"></script>
</body>
</html>
效果: