TS泛型

有人疑惑:为什么使用泛型呢,使用any不好吗?从使用方面来讲,any是可以运行的!但是遇到如下的情况就必须使用泛型:教务系统中对学校人员进行年审一个function,既需要处理student类,teacher类,也需要处理manager类,这三个类均继承自person的父类,处理哪个类实体返回哪个类实体,而使用any,显然不安全!

把泛型用在方法上

class Person {}
class Student extends Person{
    constructor(public name:string,public age:number,public check:boolean){
        super()
    }
}
class Teacher extends Person{
    constructor(public name:string,public age:number,public check:boolean){
        super()
    }
}
/**
 * 这里仅举例,不做任何业务操作
 * */
function check<T>(personal:T):T {
    return personal
}
let jack = check(new Student('jack',18,true))
let alice = check(new Teacher('alice',48,false))

当然,写代码开发时候还可以再严谨些👇,这样写限制泛型适用的范围

class Person {}
class Student extends Person{
    constructor(public name:string,public age:number,public check:boolean){
        super()
    }
}
class Teacher extends Person{
    constructor(public name:string,public age:number,public check:boolean){
        super()
    }
}
/**
 * 更严谨
 * */
function check<T extends Person>(personal:T):T {
    return personal
}
let jack = check(new Student('jack',18,true))
let alice = check(new Teacher('alice',48,false))

把泛型用在接口函数上

interface Inface<T> {
    <T>(personal:T):T;//使用泛型的匿名函数
    personal:T;//泛型属性
}
let check:<T>(personal: T) => T = function <T>(personal:T):T {
    return personal
}

把泛型用在类上

class Car {
    public price:number
    public automobileDisplacement:string
    constructor(price:number = 0,automobileDisplacement:string = '') {
        this.price = price
        this.automobileDisplacement = automobileDisplacement
    }
    action():void{
        console.log('Car run')
    }
}
class Auto extends Car {
    public name:string
    constructor(price:number = 0,automobileDisplacement:string = '',name:string = 'Auto') {
        super(price,automobileDisplacement);
        this.name = name
    }
    action():void{
        console.log(`${this.name} run`)
    }
    desc():void{
        console.log(`${this.name} sale ${this.price},automobile displacement is ${this.automobileDisplacement}`)
    }
}
class Benz extends Car{
    public name:string
    constructor(price:number = 0,automobileDisplacement:string = '',name:string = 'Benz') {
        super(price,automobileDisplacement);
        this.name = name
    }
    action():void{
        console.log(`${this.name} run`)
    }
    desc():void{
        console.log(`${this.name} sale ${this.price},automobile displacement is ${this.automobileDisplacement}`)
    }
}
// 前面代码看个大概就行,这里开始才是正餐
class MergeCar <T extends Car> {
    constructor(public car:T) {}
}
let benz:Benz = new Benz(10000,'2.0T')
let auto:Auto = new Auto(1000,'1.5L')
let mergeCar = new MergeCar(benz)
let mergeCar2= new MergeCar(auto)

扩展

我的例子代码均采用T指代泛型,T不是关键字!开发者可选其他字母,不过大多数开发者均选用的字母T指代泛型。

泛型可用多个!如下例子👇

class MergeCar <T extends Car,K extends Person> {
    constructor(public car:T,public person:K) {}
}
posted @ 2022-12-19 15:37  勤匠  阅读(118)  评论(0编辑  收藏  举报