今天继续学习 @小满zs 的 TS 课程。
1.1 函数泛型
function fn<T>(a: T, b: T): Array<T> {
return [a, b]
}
fn(1, 2) // function fn<number>(a: number, b: number): number[]
fn('1', '2') // function fn<string>(a: string, b: string): string[]
// 高阶用法
function Fn<T, K>(a: T, b: K): Array<T | K> {
return [a, b]
}
Fn(1, '鱼钓猫') // function Fn<number, string>(a: number, b: string): (string | number)[]
1.2 接口泛型
// 类型别名
type AA<T> = string | number | T
let a:AA<boolean> = false
interface B<T> {
msg: T
}
let data: B<string> = {
msg: "鱼钓猫的小鱼干"
}
应用场景:
const axios = {
get<T>(url: string): Promise<T> {
return new Promise((resolve, rejects) => {
let xhr: XMLHttpRequest = new XMLHttpRequest()
xhr.open("GET", url)
xhr.onreadystatechange = () => {
if(xhr.readyState == 4 && xhr.status == 200) {
resolve(JSON.parse(xhr.responseText))
}
}
xhr.send(null)
})
}
}
axios.get('../../document/data.json').then(res => {
console.log('res',res)
})
1.3 泛型约束
跟一个关键字 extends,后再跟类型。
function fun<T extends number>(a: T, b: T) {
return a + b
}
interface Len {
length: number
}
function fun1<T extends Len>(val: T) {
return val.length
}
- keyof:获取联合类型
let obj1 = {
name: "鱼钓猫的小鱼干",
age: 18
}
// typeof 先获取obj类型,然后 keyof 转成联合类型
type Key = keyof typeof obj1 // type Key = "name" | "age"
function fun2<T extends object, K extends Key>(data: T, key: K) {
return obj1[key]
}
fun2(obj1, 'age')
// 高级用法-----------统一改变接口
interface Data {
name: string
sex: string
age: number
}
// 遍历接口 类似 for in
type Optional<T extends object> = {
// [key in keyof T]?: T[key]
readonly [key in keyof T]: T[key]
}
type BB = Optional<Data>
// type BB = {
// readonly name: string;
// readonly sex: string;
// readonly age: number;
// }