제네릭(Generic)
- 함수나 클래스가 여러 다른 타입에서 동작할 수 있도록 하는 기능
- 제네릭은 코드의 재사용성을 높이고, 타입 안전성을 유지하며, 보다 유연한 코드를 작성할 수 있도록 해준다.
예시 - 1 비효율적인 타입선언
type SuperPrint = {
(arr:number[]):number,
(arr:string[]):number,
(arr:boolean[]):number,
}
const superPrint:SuperPrint(arr)=>{
arr.forEach((item)=>console.log(item));
}
superPrint([1,2,3]);
superPrint(["a","b","c"]);
superPrint([true,false,false]);
예시 - 2 제네릭 사용으로 코드 줄임
type SuperPrint ={
<T>(arr:T):T
}
const superPrint:SuperPrint = (arr)=>{
arr.forEach((item)=>console.log(item));
}
superPrint([1,2,3]);
superPrint(["a","b","c"]);
superPrint([true,false,false]);
superPrint([true,"a",1]);
예시 - 3 사용방법 예시
type Player<T>:{
name:string,
extraInfo:T
}
type PlayerExtra ={hp:number}
const MyPlayer = Player<PlayerExtra>;
const myPlayer:MyPlayer={
name:"temp",
extraInfo:{
hp:100
}
}