사용자 정의 타입 가드

정민교·2023년 10월 17일
0

typescript

목록 보기
12/17

📒사용자 정의 타입 가드

사용자 정의 타입 가드란 참, 거짓을 반환하는 함수를 정의하여 이 함수를 이용하여 우리가 원하는 타입 가드를 만들 수 있도록 도와주는 타입스크립트 문법입니다.

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(animal.isBark ? "짖습니다" : "안짖어요");
  } else if ("isScratch" in animal) {
    console.log(animal.isScratch ? "할큅니다" : "안할퀴어요");
  }
}

in 연산자를 이용해 타입 가드를 만들었습니다.

하지만 in 연산자를 이용하면 실제로 타입 정의를 보지 않는 이상 한 눈에 코드를 파악하기 어려워 권장하지 않는 방법이라고 전에 살펴본 적이 있습니다.

또한 in 연산자를 이용해서 타입 가드를 만들면 타입 정의 프로퍼티가 변경되는 경우에는 타입 가드가 제대로 동작하지 않게 됩니다.

예를 들면 다음과 같은 경우입니다.

type Dog = {
  name: string;
  isBarked: boolean; // isBark -> isBarked
};

Dog 타입 정의의 프로퍼티 중 isBark 프로퍼티 이름을 isBarked로 변경하게 된다면 위에 만들어둔 타입가드는 동작하지 않게 됩니다.

이럴 때 유용하게 쓸 수 있는 방법이 사용자 정의 타입 가드를 만들어 타입 좁히기를 하는 방법입니다.

(...)

// 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;
}

function warning(animal: Animal) {
  if (isDog(animal)) {
    console.log(animal.isBark ? "짖습니다" : "안짖어요");
  } else {
    console.log(animal.isScratch ? "할큅니다" : "안할퀴어요");
  }
}

이렇게 각 타입인지 확인할 수 있는 함수를 작성하여 타입 가드를 만들면 한눈에 알아보기 쉽게 타입 좁히기를 할 수 있습니다.

profile
백엔드 개발자

0개의 댓글