Basic definition
function join<T> (list:T[]) :string{
return list.join(', ')
}
join<string> (['coco'.'jeck'])
Copy the code
A generic interface
interface join {
<T>(args:T[]):string
}
interface Man<T>{
name:string
race:T
}
Copy the code
A generic class
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)
Copy the code
Generic constraint
interface Iprop{
length:number
}
// The length attribute must be included
function getLength<T extends Iprop> (list:T) :number{
return list.length
}
getLength([1.2.3])
getLength({ length: 10 })
Copy the code
Using class types
function create<T> (c: {new(): T; }) :T {
return new c();
}
Copy the code