Digking's cave

TypeScript 기본 / 기초문법 ) Overloading 본문

기초/TypeScript

TypeScript 기본 / 기초문법 ) Overloading

디깅 2022. 8. 24. 00:05
728x90

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
    return a + b
}
Router.push({
    path : "/home",
    state:1
})

위와 같이 라우터 기능에서 home으로 페이지 이동하라는 내용의 코드를 

아래의 오버로딩 사용한 코드로 작성 가능하다.

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

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

 

다른 여러개의 argument를 가지고 있을 때도 사용할 수 있다.

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
}

call signature의 매개변수가 다르기 때문에,

이 때 c는 옵션이다. 

c는 number라는 걸 알려주기 위해 물음표를 붙여주고, c가 있는 경우와 없는경우 각각에 대해 return 설정해준다.

반응형