.
본문 바로가기
TypeScript

여러가지 형태의 타입가드

by 와칸다개발자 2022. 5. 9.

https://www.youtube.com/watch?v=ViS8DLd6o-E&t=3158s 

이 게시글은 위 영상에서 타입가드 부분을 정리하고 기록한 것임.

 

타입 가드는 타입 추론의 범위를 좁혀주는 것.

1. 원시 객체 타입가드

function getNumber(n: number | string):number {
	// n <- number | string;
	if(typeof n === 'number'){
    	// 여기 스코프 안에서 넘버로 추론
    	return n;
    }
	// n <- string;
}

위 함수 if문 스코프 안에서 n은 넘버로 추론된다.

 

 

2. Instanceof Type Guard

interface IMachine{
	name:string;
}

class Car implements IMachine{
	name:string;
    wheel:number;
}

class Boat implements IMachine{
	name:string;
    motor:number;
}

function getWheelorMotor(machine: Car | Boat):number{
	if(machine instanceof Car){
    	reuturn machie.wheel; // Car
    }else{
    	return machine.motor;  // Boat
	}
}

 말 그대로 머신 파라미터가 어느 객체의 인스턴스인가를 판단하여 추론

 

instance of typeguard는 다음 예제에서 많이 쓰인다.

class NumberError extends Error{}

function getNumber(n:number) :number | NumberError {
	if(n < 0){
    	return new NumberError();
	}
    return n;
}

const num = getNumber(-1234124);
if(num instanceof NumberError){
	return;
}

num // number로 추론

예외처리를 할 때 예외를 만들어서 리턴해야 할 경우 

 

만약 n이 0 보다 작아서 예외 객체를 리턴해야 한다면 컴파일 시 num 변수는 

 

NumberError 객체를 받아올 수 없기 때문에 instanceof 로 타입을 추론해야 한다.

 

 

3. object의 속성유무로 타입 가드

interface Admin{
	id:string;
    role:string;
 }
 
 interface User{
 	id:string;
    email:string;
 }
 
 function redirect(user: Admin | User){
 	if('role' in user){
    	console.log('관리자'):
    }else{
    	console.log('유저');
	}
 }

 

 

4. 리터럴 타입가드 - object의 속성이 같고 타입이 다른경우

 

이 코드는 리듀서를 작성할 때 많이 봤다.

interface IMachine{
	type:string;
}

class Car implements IMachine{
	type:'CAR';
    wheel:number;
}

class Boat implements IMachine{
	type:'BOAT';
    motor:number;
}

function getMotororWheel(machine: Car | Boat):number {
	if(machine.type === 'CAR'){
    	return machine.wheel;
    }else{
    	return machine.motor;
	}
}

 

 

5. 커스텀 타입 가드

위 4가지 타입 가드 경우를 제외하고 커스텀하게 사용하고 싶은경우

function getWheelorMotor(machine:any):number {
	if(isCar(machine)){
    	return machine.wheel;
    } else if(isBoat(machine)){
    	return machine.motor;
    }
    return -1 ;
}

function isCar(arg:any): arg is Car  {
	return arg.type === 'CAR';
}

function isBoat(arg:any): arg is Boat  {
	return arg.type === 'BOAT;
}

 

isCar 함수는 리턴할 때 true로 판단될 경우 위 arg is Car 타입 서술어로 

 

arg 의 타입이 Car임을 추론해준다. 

 

댓글