基础定义
代码语言:javascript
复制function join<T>(list:T[]):string{
return list.join(',')
}
join<string>(['coco', 'jeck'])
泛型接口
代码语言:javascript
复制interface join {
<T>(args:T[]):string
}
interface Man<T>{
name:string
race:T
}
泛型类
代码语言:javascript
复制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)
泛型约束
代码语言:javascript
复制interface Iprop{
length:number
}
// 必须包含length属性
function getLength<T extends Iprop>(list:T):number{
return list.length
}
getLength([1, 2, 3])
getLength({ length: 10 })
使用类类型
代码语言:javascript
复制function create<T>(c: {new(): T; }): T {
return new c();
}