基础定义
function join<T>(list:T[]):string{
return list.join(',')
}
join<string>(['coco', 'jeck'])
泛型接口
interface join {
<T>(args:T[]):string
}
interface Man<T>{
name:string
race:T
}
泛型类
class Man<T>{
name:string
rece:T
constructor(name:string, rece:T){
this.name = name
this.rece = rece
}
}
const Coco = new Man<number>('Coco', 1)
泛型约束
interface Iprop{
length:number
}
// 必须包含length属性
function getLength<T extends Iprop>(list:T):number{
return list.length
}
getLength([1, 2, 3])
getLength({ length: 10 })
使用类类型
function create<T>(c: {new(): T; }): T {
return new c();
}
网友评论