TypeScript基础学习(6): 泛型

泛型: 可以支持不特定的数据类型 要求: 传入的参数和返回的参数一致

function getData(value: T):T {
    return value
}
getData(123)
getData('123')

泛型类: 传入数字返回数字,传入字符串返回字符串

class MinClass  {
    public list:number[] = [];
    add (num:number) {
        this.list.push(num)
    }
    min():number {
        var minNum = this.list[0]
        for (let i=0;i this.list[i]) {
                minNum = this.list[i]
            }
        }
        return minNum
    }

}
class MinClass2 {
    public list:T[] = [];
    add (num:T):void {
        this.list.push(num)
    }
    min():T {
        var minNum = this.list[0]
        for (let i=0;i this.list[i]) {
                minNum = this.list[i]
            }
        }
        return minNum
    }
}
let minNum = new MinClass2() // 实例化类,并制定类的T代表的类型是number
minNum.add(1)
minNum.add(2)
minNum.add(3)
console.log(minNum.min()) // 1

类作为参数约束传入数据

// 类作为参数约束传入数据
class User {
    username: string | undefined;
    password: string | undefined;
}
class MysqlDB {
    add(user: User):boolean {
        console.log(user)
        return true
    }
}
let user = new User()
user.username = 'z'
user.password = '123456'
let mysql = new MysqlDB()
mysql.add(user)

// 泛型类
class MysqlDB2 {
    add(user: T):boolean {
        console.log(user)
        return true
    }
}
class User2 {
    username: string | undefined;
    password: string | undefined;
}
let user2 = new User2()
user2.username = 'z'
user2.password = '123456'
let mysql2 = new MysqlDB2()
mysql2.add(user2)

你可能感兴趣的:(typescript)