Typescript에서의 function overloading

유재헌·2023년 2월 2일
0

Typescript

목록 보기
5/8

Function Overloading

  • 직접 작성하기보다 외부 라이브러리에 자주 보이는 형태로,
  • 하나의 함수가 서로 다른 여러개의 call signature를 가질 때 발생한다.

단순한 예시)

type Add = {
  (a: number, b: number) : number,
  (a: number, b: string) : number
}

const add: Add = (a, b) => {
  if(typeof b === "string") return a //⭕b가 string이면 return값이 number
  return a + b //⭕return값이 number
}

많이 접할 수 있는 예시)

  • Next.js에서 우린 여러 Router를 만들게 된다.
  • 그런데 그 라우터를 string으로 보낼 수도 있지만 Object(객체) 형식으로 보낼 수도 있다.
  • 오버로딩의 좋은 예시이다.
Router.push("/home")
//또는
Router.push({
  path: "/home",
  state: 1,
})

실전예시)

type Config = {
  path: string,
  state: object
}

type Push = {
  (path: string): void,
  (config: Config): void,
}

const push: Push = (config) => {
  if(typeof config === "string") {
    console.log(config)
  } else {
  console.log(config.path)
  }
}

주의할 점

type Add = {
  (a: number, b: number): number,
  (a: number, b: number, c: number): number,
}

const add: Add = (a, b, c?:number) => {
  if(c) return a + b + c
  return a + b;
}

add(1, 2)
add(1, 2, 3)
  • 위와 같이 두 개 이상의 call signature들의 parameter의 개수가 다를 때,
    c의 경우 옵션이기 때문에 함수를 호출할 때
    c의 타입이 아마도 number일 것이다(c?:number) 라고 코드에 적어줘야 한다.
profile
possibilities

0개의 댓글