all is well!!

16. [Ts] Polymorphism / Generic 본문

[Nextjs + Typescript] velog 클론코딩/[ Nextjs + Typescript ] 나를 위한 기록

16. [Ts] Polymorphism / Generic

tnqlscho 95 2023. 3. 10. 21:33

Polymorphism

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

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

const a = superPrint([1,3,9])
const b = superPrint([‘1’,’3’,’9’])
const c = superPrint([false,3,9])

 

함수에 따라서 넣는 매개변수에 따라 Call signatures 형태의 다양성을 가질 수도 있다.

 

Generic

하지만 매개변수에 들어올 확실한 타입을 모르는 Call signatures의 다향성에 대한 경우의

Call signatures 전부 기재하기 힘들거나 애매할때가 있다.

type SuperPrint = {
    <T>(arr: T[]): T
}

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

const a = superPrint([1,3,9])
const b = superPrint([‘1’,’3’,’9’])
const c = superPrint([false,3,9])

그럴때 generic을 쓰면 concrete type(number,string,boolean…)을 사용하는것 대신에

typescript에게 generic 타입을 쓸거라고 알려주는 것으로 typescript가 어떤 타입인지 추론하게 해서

간단하게 각 매개변수 type에 맞는 Call signatures을 생성할 수 있다.

(+ 그리고 generic 이름은 내가 원하는 이름으로 지정할 있다.)

 

 

* 같은 type generic 두개 이상으로 지정하고 싶을때

type SuperPrint = {
    <T,M>(arr: T[], arr2: M): T
}

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

const a = superPrint([1,3,9], ’M’)
const b = superPrint([‘1’,’3’,’9’], ’M’)
const c = superPrint([false,3,9], ’M’)

 

* generic 함수에 바로 적용할때

function superPrint<T>(a: T[]){
    Return a[0]
}

const a = superPrint([1,3,9], ’M’)
const b = superPrint([‘1’,’3’,’9’], ’M’)
const c = superPrint([false,3,9], ’M’)

 

* type 확장할때의 generic

type Player<E> ={
    name:string
    extraInfo : E
}

typescript가 스스로 타입추론하게 하는것이 제일 좋다.

generic 사용해서 type 생설할 수도 있고 type 확장할 수도 있다.

 

type Player extraInfo type 다향성을 주어야 될때 이렇게 사용할수 있다.

type Player<E> ={
    name:string
    extraInfo : E
}

Type Extra = {
    favFood: ’string’
}

Type subinPlayer = Player<Extra>

Const subin: subinPlayer = {
    Name: ‘subin’,
    extraInfo: {
        favFood: ‘kimchi’
    }
}

const Lynn: Player<null> = {
    name: ‘Lynn’,
    extraInfo: null
}

그리고 기존의 type에 커스텀 generic으로 변경해줄수도 있다.

이렇게 type 생성하고 . type 또다른 type 넣어서 사용할 있다.

 

 

 

 

 

*출처 [노마드코더 ts 강의]

https://nomadcoders.co/typescript-for-beginners/lectures/3677

https://nomadcoders.co/typescript-for-beginners/lectures/3676

https://nomadcoders.co/typescript-for-beginners/lectures/3674

'[Nextjs + Typescript] velog 클론코딩 > [ Nextjs + Typescript ] 나를 위한 기록' 카테고리의 다른 글

18.[Ts] Interface  (0) 2023.03.15
17. [Ts] Abstract class  (0) 2023.03.13
15. [Ts] Overloading  (0) 2023.03.08
14. [Ts] Call signatures  (0) 2023.03.07
13. [Ts] readonly  (0) 2023.02.24
Comments