all is well!!

15. [Ts] Overloading 본문

Overloading

앞에서 call signatures는 이렇게 간단하게 작성할수도 있지만

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

 오버로딩을 위해서 이렇게 작성할 수도 있다.

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

 

오버로딩은 외부 라이브러리에 자주 보이는 형태로 함수가 여러개의 다른type의 call signatures를 가질때 발생한다.

그리고 next.js에서 라우팅때도 연관되어 있다.

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)}
}

if의 리턴값은 string으로 인지하고

else의 값은 객체로 인식하게 된다.

 

 

* 다른 갯수의 argument를 가지고 있을때

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

이렇게 다른 call signatures에 파라미터 갯수도 다를때

c는 있을때도 있고 없을때도 있을 수 있는 옵션으로 파악해서

 

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

add 함수 매개변수에 ‘c는 있을때는 number인데 없을때도 있어.’라는 의미로

c?:number 이렇게 옵셔널을 지정해준다.

 

 

 

 

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

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

Comments