포시코딩

[TypeScript][노마드코더] #3 FUNCTIONS(1) 본문

JavaScript

[TypeScript][노마드코더] #3 FUNCTIONS(1)

포시 2023. 1. 17. 19:09
728x90

Call Signature

type Add = (a: number, b: number) => number;

const add:Add = (a, b) => a + b;

먼저 함수의 타입을 설명하고 나서 코드를 구현하는 방법

 

Overloading(오버로딩)

오버로딩은 함수가 여러 개의 call signature를 가지고 있을 때 발생시킨다.

그냥 여러 개가 아닌 서로 다른 여러 개의 call signature을 가졌을 때!

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

const add:Add = (a, b) => a + b;  // Error! b가 number or string이라 string과 number를 더할 수 없다.

 

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

const add:Add = (a, b) => {
  if (typeof b === 'string') return a
  return a + b
}

 

react의 Next에서의 실제 예시)

Router.push('/home')

Router.push({
  path: '/home', 
  state: 1
})

String으로 보낼 수도 있고, Object로도 보낼 수 있다.

위와 같은 상황일 때를 TypeScript로 나타내면 다음과 같다.

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, config.state)
  }
}

 

parameter 개수가 다른 경우

type Add = {
  (a: number, b: number): number
  (a: number, b: number, c: number): number  // c는 옵션인 경우
}

const add: Add = (a, b, c) => {  // Error!
  return a + b
}

const add: Add = (a, b, c?: number) => { // c는 아마 number일 것이다 라는걸 알려줘야 한다.
  if (c) return a + b + c
  return a + b
}

add(1, 2)
add(1, 2, 3)

다른 개수의 파라미터라 에러 발생하는데 c를 옵션으로 지정해서

위와 같은 방식으로 표현한다면 해결된다.

728x90