본문 바로가기

공부/TypeScript

타입스크립트 챌린지 (4)

#3.2 Polymorphism

Concrete type

  • number, string, void, unknown...
type SuperPrint = {
    (arr:number[]) : void
    (arr:boolean[]) : void
    (arr:string[]) : void
}

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

superPrint([1,2,3])

Generic type

  • Generic type이란 type의 placeholder와 같은 개념
  • call signature를 작성할 때, 확실한 타입을 모를때 함수가 추론하도록 사용
type SuperPrint = {
    <T>(arr:T[]) : void
}

 

- return 값이 있는 함수

type SuperPrint = <T>(arr:T[]) => T
const superPrint : SuperPrint = (arr) => arr[0];

const a = superPrint(["hi", true, 30])

 

- 여러 arguments

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

const superPrint : SuperPrint = (arr) => arr[0];

const a = superPrint(["hi", true, 30], "lena");

 

- 함수의 generic 표현

function newFn<T>(a:T[]){
    return a
}

 

- Obj 생성 시 {} generic 표현 

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

const nico:Player<{}> = {
    name: "Nico",
    extraInfo: {
        
    }
}

 

- Generic의 또 다른 표현식 

type A = Array<number>;
let a:A = [1,2,3];