[TypeScript] Overloading

jr_necki·2022년 8월 22일
0

TypeScript

목록 보기
4/7
post-thumbnail

✔ Overloading ??

오버로딩은 함수가 서로 다른 여러개의 call signatures를 가지고 있을 때 발생한다.

파라미터 타입이 다를 경우

파라미터 타입이 다를 경우에, if문으로 나누어서 처리 할 수 있다.

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

push함수의 config 파라미터 타입은 string | Config이 될 수 있고,
이는 if문으로 나눌 수 있다.

파라미터 개수가 다를 경우

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

c파라미터는 있는것과 없는 것이 있으므로

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

optional로 정해주면 된다.


물론 이렇게 해도 된다.^^

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

0개의 댓글