泛型
回顾一下泛型
let arr: Array<number> = [1, 2, 3]
console.log(arr)
// [ 1, 2, 3 ]
不用泛型
interface IGoods {
name: string
}
class shoppingCart {
goods: IGoods
constructor(goods: IGoods) {
this.goods = goods;
}
}
泛型示例
interface IGoods {
name: string
}
interface IChild {
name: string
age: number
}
class shoppingCart<T> {
t: T
constructor(t: T) {
this.t = t;
}
}
let a1 = new shoppingCart<IGoods>({name: '西瓜'})
console.log(a1)
// shoppingCart { t: { name: '西瓜' } }
let a = new shoppingCart<IChild>({name: 'Tom', age: 4})
console.log(a)
// shoppingCart { t: { name: 'Tom', age: 4 } }
使用了泛型之后,代码具有更好的可扩展性,成员变量的类型,不是来自于类内部,而是来自外部声明,修改的时候对代码的侵入性就小了很多
函数中使用泛型
interface IChild {
name: string
}
interface ICat {
name: string
}
function say<T>(t: T){
console.log(t)
}
say<IChild>({name: 'Tom'})
// { name: 'Tom' }
say<ICat>({name: 'cat'})
// { name: 'cat' }