ts泛型08

泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性

 

// 需求:定义一个函数,传入两个参数,第一个参数是数据,第二个参数是数量,
// 函数的作用:根据数量产生对应个数的数据,存放在一个数组中
function GetaArr<T>(value: T, count: number): T[] {     //T:任意类型数值
    const arrValue: T[] = []
    for (let i = 0; i < count; i++) {
        arrValue.push(value)
    }
    return arrValue
}
//不建议使用any
// 使用泛型的话,在定义的时候不需要先确定好类型,等到使用的时候再去确定
// 如果没有使用的话,就会走自动推断
console.log(GetaArr(99, 3))
console.log(GetaArr<string>("99", 3))

// 多个泛型互换
function PostArr<T, U>(t: [T, U]): [U, T] {     //T:任意类型数值
    return [t[1], t[0]]
}
console.log(PostArr<string, number>(["99", 3]))
console.log(PostArr<number, string>([3, "99"]))

// 泛型约束
interface Xlength {
    length: number
}
function ArrLength<T extends Xlength>(x: T): number {
    return x.length
}
console.log(ArrLength("123456789"))

// 泛型接口
interface IArr {
    <T>(value: T, count: number): Array<T>
}
let portArr: IArr = function <T>(value: T, count: number): T[] {     //T:任意类型数值
    const arrValue: T[] = []
    for (let i = 0; i < count; i++) {
        arrValue.push(value)
    }
    return arrValue
}
console.log(portArr("9999", 9))

class Pers<T>{
    constructor(public name: T, public age: T) { }
}
const person1 = new Pers<string>("111", "222")
const person2 = new Pers<number>(111, 222)
const person3 = new Pers<string | number>("111", 222)
console.log(person1)
console.log(person2)
console.log(person3)

  

posted @ 2024-02-21 18:30  文采呱呱  阅读(1)  评论(0编辑  收藏  举报