Skip to main content

Generic

  • Generics allow us to define reusable functions and classes that can have multiple types
  • Syntax is messy but is used a lot

Simple Generic

function numIdentity(item:number):number{
return item;
}
function stringIdentity(item:string):string{
return item;
}
function boolIdentity(item:boolean):boolean{
return item;
}

//can be written as follows, to accept parameter of that type and return value of that type
function identity<Type>(item:Type): Type {
return item;
}
//使用它
identity<number>(7)
identity<string>("hello")

Array of Generic

function getRandom<T>(list:T[]):T{
const randIndex = Math.floor(Math.random()*list.length);
return list[randIndex];
}
getRand<number>([1,2,3,4,5])
getRand<string>(["a","b","c"])