본문 바로가기

Web_Study/TypeScript

TypeScript_6:Generic_2

실제 Generic을 이용한 코드를 작성할 때, CallSignature를 만들 일은 거의 없음

  • 라이브러리를 만들거나 다른 개발자가 사용할 기능을 개발하는 경우엔 Generic을 이용하여 CallSignature 생성이 유용할 것
  • 주로 외부 패키지/라이브러리를 사용하며 그 라이브러리들을 Generic을 통해 생성하는 방식으로 코딩

 

Generic 활용

  • 함수 인자 Type을 Generic 설정
function funcA<T>(a:T[]){
	return a[0]
}

 

  • 함수 인자 Type을 Generic 설정_2
type Player<E>={
	name:string,
    extraInfo:E
}

const yjh:Player <{favFood:string}> = {
	name:"YJH",
    extraInfo:{
    	favFood:"protein"
    }
}

const alice:Player<null>={
	name:"alice",
    extraInfo:null
}
// 이처럼 extraInfo에 값을 넣고 싶지 않을 경우, null type작성

 

  • Type 생성 후, 그 Type을 다른 Type안에 재사용 가능
    • 많은 것들이 존재하는 큰 Type안에 변동성이 있는 Type을 따로 재사용함으로써 코드 작성의 효율성
type yjhExtra={
	favFood:string
}

type yjhPlayer = Player<yjhExtra>

 

  • 많은 외부 라이브러리/패키지를 확인하게 되면 아래 이미지와 같이 제네릭을 사용한 타입이 지정된 함수를 줄것
  • 어떤 Type을 사용할 것인지만 명시해주면 사용가능

function printAllNumbers(arr:Array<number>){ //Array 라이브러리에서 number라는 type사용할 것이라 명시

}


useState<number>()
//ReactJS에서 자주사용되는 useState또한 Generic을 제공하는데, 
//위와 같이하면 state값을 number type으로 사용할것이라 명시하는 것

 

'Web_Study > TypeScript' 카테고리의 다른 글

TypeScript_8:Class_2  (0) 2022.06.10
TypeScript_7:Class  (0) 2022.06.07
TypeScript_5:Polymorphism & Generic  (0) 2022.05.31
TypeScript_4:CallSignature & Overloading  (0) 2022.05.26
TypeScript_3:Types_2  (0) 2022.05.25