오버로딩 - 함수는 하나, 매개변수의 갯수 or 타입에 따라 다르게 구현되도록 하는 것

함수의 선언부와 구현부로 나눠서 살펴보자면 

 

☘️선언부 (오버로드 시그니쳐) - 다양한 버전을 나타냄

 
     function foo(a:number):void; //foo의 버전1
     function foo(a:number,b:number,c:number):void; //foo의 버전2
 

 

☘️ 구현부

 
 
   function foo(a:number, b?:number, c?:number) {
        if(typeof b === "number" && typeof c === "number") {
            console.log("버전2일 때의 구현부")
        } else {
            console.log("버전1일 때의 구현")
        }
    }
 

 

이 때 버전1과 버전2는 매개변수가 1개, 3개이므로 

 
   foo(1,2) //오류
 

 

 

사용자 정의 타입가드

참,거짓을 반환하는 함수를 이용해 타입 좁히기를 할 수 있게 해준다.

type Dog = {
	name:string;
	isBark:boolean;
}

type Cat = {
	name:string;
	isScratch:boolean;
}

type Animal = Dog | Cat;

function warning(animal:Animal) {
	if("isBark" in animal) {
     	console.log('개타입')
    } else if ("isScratch" in animal) {
    	console.log('고양이타입')
    }
}

 

물론 in 타입가드를 사용해도 좋지만, 직관적이지 않을뿐더러 타입의 프로퍼티 네임이 변경되면 오류 발생 가능성이 있기 때문에 

//dog타입인지 확인하는 타입 가드
function isDog(animal:Animal): animal is Dog{
	return (animal as Dog).isBark !== undefined
}

//cat타입인지 확인하는 타입 가드
function isCat(animal:Animal): animal is Cat {
	return (animal as Cat).isScratch !== undefined
}

 

 animal is Dog/Cat의 의미 - isDog / isCat 함수가 true를 반환하면 Dog / Cat 타입임을 보장한다.

리턴문에서 as 단언문을 쓴 이유는 isBark는 Animal타입과 Cat타입에서 찾을 수 없는 프로퍼티라서 오류가 발생하기때문이다.

function warning(animal:Animal){
	if(isDog(animal)){
		console.log('개타입')
	} else if (isCat(animal)) {
		console.log('고양이타입')
	}
}

 

결과적으로 warning 함수에서의 타입 좁히기는 이렇게 바꿔쓸 수 있다.

+ Recent posts