[typescript]타입 가드 활용

jaejin·2023년 4월 2일

카카오 테크 블로그에서 본 내용을 정리해두려고 쓰는 글.

1. in 키워드

// in 키워드 사용

function printInfo(content: Webtoon | WebNovel) {
  if ("isFinish" in content) {
    // isFinish 가 있으니 이건 Webtoon 이다.
    console.log(content.isFinish); // ✅ OK - content: Webtoon
  } else {
    console.log(content.age); // ✅ OK - content: WebNovel
  }
}
  • union type에서 활용 가능
  • 케이스가 많은 union type이나 공통된 속성만 가지는 경우에는 부적절

2. Tagged Union Types

// Tagged Union Types

interface Webtoon {
  type: "webtoon";
  title: string;
  episode: number;
  isFinish: boolean;
}

interface WebNovel {
  type: "webNovel";
  title: string;
  episode: number;
  age: "all" | 12 | 15 | 19;
}

interface SF {
  type: "sf";
  title: string;
  episode: number;
  price: 3000;
}

function printInfo(content: Webtoon | WebNovel | SF) {
  switch (content.type) {
    case "webtoon":
      return content.isFinish; // ✅ OK - content: Webtoon
    case "webNovel":
      return content.age; // ✅ OK - content: WebNovel
    case "sf":
      return content.price; // ✅ OK - content: SF
  }
}
  • union type에서 활용 가능
  • 타입의 종류가 많아지면 type과 같은 공통 속성을 추가해서 타입 가드를 활용할 수 있다.

3. assert

// 예시 1
function assert(value: any, errorMsg: string): asserts value {
  if (!value) throw new Error(errorMsg);
}

function toString(value?: number) {
  assert(value !== undefined, "value 는 undefined 가 아니어야 한다.");
  return value.toFixed(2);
}


// 예시 2
function getNickname(name: string | null): string {
  assert(name != null) // true

  return name // string
}

getNickname('fronttigger') // fronttigger
  • 타입스크립트 3.7부터 가능한 방법
  • 인자로 입력받은 condition이 true인 경우 조건이 포함하는 범위의 나머지 부분에 대한 타입을 보장받는다.

4. "is" operator

https://velog.io/@songjj77/typescript-타입스크립트-팁들from-Medium
이미 썼던 내용이라 링크로 대체

참조
https://www.fronttigger.dev/2022/typescript/type-guard
https://fe-developers.kakaoent.com/2021/211012-typescript-tip/#4-타입-가드-활용하기

profile
jjlabsio

0개의 댓글