[Typescript] 타입스크립트 타입 가드

problem_hun·2023년 3월 21일
0

타입스크립트

목록 보기
14/16
post-thumbnail

타입 가드

어떤 변수의 타입이 여러가지일 때, 타입이 A인 경우와, B인 경우를 나눠서 다른 동작을 수행시킬 수 있다. 이를 타입 가드라고 한다.

interface Developer {
  name: string;
  skill: string;
}
interface Person {
  name: string;
  age: number;
}

function introduce(): Developer | Person {
  return { name: 'jihu', age: 25, skill: 'coding' };
}
var jihu = introduce();
console.log(jihu.skill); //❌❌❌

위의 코드에서 jihu.skill을 콘솔로그하려면 에러가 난다. 유니언 타입은 공통된 속성에만 접근 가능하므로 에러가 나는 것이다.

if ((jihu as Developer).skill) {
  console.log((jihu as Developer).skill);
} else if ((jihu as Person).age) {
  console.log((jihu as Person).age);
}

콘솔로그를 하려면 위와같이 타입 단언을 계속 써가며 타입을 확정시킨 후에 콘솔로그를 해야 한다.

 

타입 가드 예제

하지만 아래와 같이 타입 가드를 사용하여 어떤 타입인지 boolean값으로 받게 되면 간단하게 타입 판단을 할 수 있게 된다.
리턴할 타입을 적는 곳에 <파라미터> is <판단할 타입> 키워드로 판단할 타입을 지정한 후에 return문에 그 타입인지 판단할 수 있는 조건을 적어주면 된다.

function isDeveloper(target: Developer | Person): target is Developer {
  return (target as Developer).skill !== undefined;
}

if (isDeveloper(jihu)) {
  console.log(jihu.skill);
} else {
  console.log(jihu.age);
}
profile
문제아

0개의 댓글