Digking's cave

TypeScript 기본 / 기초문법 ) Polymorphism / Generic 본문

기초/TypeScript

TypeScript 기본 / 기초문법 ) Polymorphism / Generic

디깅 2022. 8. 24. 11:30
728x90

다형성 Polymorphism

/ Generic

generic은 call signature 작성할 때 들어오는 type을 확실히 모를 때 사용한다.

 

어떤 타입이 들어올지 모르고, 다양한 경우에 대비를 해야하는 경우 concrete type은 모든 경우를 다 작성해야 한다.

예시)

type SuperPrint = {
    (arr: number[]) : void
    (arr: boolean[]) : void
    (arr: string[]) : void
    (arr: (string | number)[]) : void
}

const superPrint : SuperPrint = (arr) =>{
    
    arr.forEach(i => console.log(i))
}

superPrint([1,2,3,4])
superPrint([true,false])

superPrint([1,2,true,false]) // 이 경우는 대비되지 않아서 error 발생

 

하지만 모든 경우의 수를 다 대비하기 어렵기 때문에 generic을 사용해서 대비하는 코드를 작성할 수 있다.

TypePlaceHolder 에는 원하는 이름을 작성하면 된다. (보통 T 사용)

// void
type SuperPrint = {
    <TypePlaceHolder>(arr:TypePlaceHolder[]) : void
}

//return 값 있는 경우
type SuperPrint = {
    <TypePlaceHolder>(arr:TypePlaceHolder[]) : TypePlaceHolder
}

const superPrint : SuperPrint = (arr) =>{
    
    arr.forEach(i => console.log(i))
}

superPrint([1,2,3,4])
superPrint([true,false])

superPrint([1,2,true,false])

 

Generic을 여러개 지정할 수 있다.

type SuperPrint = {
    <T,M>(a:T[].b:M) : T
}

 

▶ Genric은 내가 원하는대로 signature를 생성해주는 도구이다.

 

- Generic의 type으로 객체가 올 수도 있다.

 - type끼리 재사용을 할 수 있다.

type Player<E> ={
    name : string,
    extraInfo : E
}
//많은 것들이 있는 큰 타입 내에서 하나가 달라질 수 있다면, Generic을 사용하면 된다.

type NicoExtra = {
    favFood : string
}

type NicoPlayer = Player<NicoExtra>

const nico : NicoPlayer = {
    name : "nico"
    extraInto: {
        favFood: "kimchi"
   ]
}

const lynn : player<null> = {
    name : "lynn"
    extraInto: null
}

 

Array에서도 generic이 사용된다.

number[] 는 Array<number> 와 같다.

 

반응형