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) {} }
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/p/16992325.html