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

function getData<T>(value: T):T {
    return value
}
getData<number>(123)
getData<string>('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.length;i++) {
            if (minNum > this.list[i]) {
                minNum = this.list[i]
            }
        }
        return minNum
    }

}
class MinClass2<T> {
    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.length;i++) {
            if (minNum > this.list[i]) {
                minNum = this.list[i]
            }
        }
        return minNum
    }
}
let minNum = new MinClass2<number>() // 实例化类,并制定类的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<T> {
    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<User2>()
mysql2.add(user2)

流年朝朝
128 声望12 粉丝

但行好事,莫问前程