Javascript/TypeScript

[TypeScript] 오버로딩 (Overloading)

뉴벡엔드 2024. 3. 13. 15:44

 

오버로딩(Overloading)

동일한 이름의 함수에 파라미터 개수나, 타입을 다르게 하여 함수를 만드는 것

 

 

 

매개변수의 개수가 같고 타입이 다를 때

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

const test1:Test1 = (a,b) =>{
    if(typeof a ==="string") console.log(a)
    else return console.log(a+b)
}

 

 

 

매개변수의 개수가 다를 때

 

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

const test2:Test2 = (a,b,c?:number) =>{
    if(c) console.log(a+b+c )
    else return console.log(a+b)
}
 
 

 

 또 다른 예제

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

 

 

 

참고:https://nomadcoders.co/typescript-for-beginners

반응형

'Javascript > TypeScript' 카테고리의 다른 글

[TypeScript] 속성값 제한하기  (0) 2024.03.13
[TypeScript] 제네릭(Generics) 사용하는 이유  (0) 2024.03.13
[TypeScript] Call Signatures  (0) 2024.03.13
[TypeScript] unknown  (0) 2024.03.13
[TypeScript] readonly  (0) 2024.03.13