TypeScript 타입 가드(Type Guards)란?

jinew·2025년 3월 18일

🍏 TypeScript

목록 보기
5/7
post-thumbnail

🛡️ TypeScript 타입 가드(Type Guards)란?

타입스크립트를 사용하다 보면 여러 개의 타입을 가질 수 있는 값(예: string | number)을 처리해야 하는 경우가 많다. 이때 타입 가드(Type Guards)를 사용하면 코드에서 특정 타입을 안전하게 판별하고 사용할 수 있다고 한다.

이번 글에서는 타입 가드의 개념과 활용법을 알아보자!



1️⃣ 타입 가드란?

타입 가드는 런타임에서 값의 타입을 확인해 특정 타입으로 좁혀주는 기법이다.
타입스크립트는 정적인 타입 시스템을 제공하지만, 실행 시점에서는 실제 값의 타입을 확인해야 하는 경우가 있다. 예를 들어 API 응답으로 string | number 타입을 받을 때, 해당 값을 숫자로 연산할지 문자열로 처리할지 구분해야 한다.

function processValue(value: string | number) {
  if (typeof value === "string") {
    console.log("문자열 변환:", value.toUpperCase());
  } else {
    console.log("숫자 연산:", value * 2);
  }
}

processValue("hello"); // 문자열 변환: HELLO
processValue(10); // 숫자 연산: 20

위 코드에서는 typeof를 활용하여 valuestring이면 대문자로 변환하고, number면 연산을 수행하도록 타입을 좁혔다. 이처럼 값의 타입을 확인해 타입별로 이후 처리가 가능하다는 점에서 안정성을 확보할 수 있다는 큰 장점이 있다.



2️⃣ 기본적인 타입 가드

1. typeof 연산자 활용

자바스크립트이 typeof 연산자는 기본 타입인 string, number, boolean, object, function, undefined, symbol, bigint를 확인하는 데 유용하다.

function printLength(value: string | number) {
  if (typeof value === "string") {
    console.log("문자 길이:", value.length);
  } else {
    console.log("숫자 자체는 길이를 가질 수 없음");
  }
}

2. instanceof 연산자 활용

클래스의 인스턴스를 판별할 때는 instanceof를 사용할 수 있다.

class Dog {
  bark() {
    console.log("멍멍!");
  }
}

class Cat {
  meow() {
    console.log("야옹!");
  }
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark();
  } else {
    animal.meow();
  }
}


3️⃣ in 연산자를 활용한 타입 가드

in 연산자를 사용하면 객체가 특정 속성을 가지고 있는지를 확인하여 타입을 좁힐 수 있다.

type User = { name: string; email: string };
type Admin = { name: string; role: string };

type Person = User | Admin;

function printUserInfo(person: Person) {
  if ("email" in person) {
    console.log("사용자 이메일:", person.email);
  } else {
    console.log("관리자 역할:", person.role);
  }
}

const user: User = { name: "Alice", email: "alice@example.com" };
const admin: Admin = { name: "Bob", role: "superadmin" };

printUserInfo(user); // 사용자 이메일: alice@example.com
printUserInfo(admin); // 관리자 역할: superadmin

위 코드에서 "email" in person을 사용해 User 타입인지를 판별했다.
in 연산자는 인터페이스 또는 객체 리터럴 타입을 구분하는 데 매우 유용하다. 특히 API 응답을 처리할 때 활용할 수 있다.



4️⃣ 사용자 정의 타입 가드 (is 키워드 활용)

in 연산자를 사용하면 객체가 특정 속성을 가지고 있는지를 확인하여 타입을 좁힐 수 있다.

type Dog = { bark: () => void };
type Cat = { meow: () => void };

type Animal = Dog | Cat;

function isDog(animal: Animal): animal is Dog {
  return (animal as Dog).bark !== undefined;
}

function makeSound(animal: Animal) {
  if (isDog(animal)) {
    animal.bark(); // Dog 타입으로 좁혀짐
  } else {
    animal.meow(); // Cat 타입으로 좁혀짐
  }
}

위 코드에서 isDog 함수는 animal is Dog를 반환하는 사용자 정의 타입 가드이다. 이를 사용하면 if (isDog(animal)) 내부에서 타입이 Dog로 좁혀진다.



5️⃣ 타입 가드 활용 사례

1. API 응답 데이터 처리

type SuccessResponse = { success: true; data: string };
type ErrorResponse = { success: false; error: string };

type APIResponse = SuccessResponse | ErrorResponse;

function handleResponse(response: APIResponse) {
  if (response.success) {
    console.log("응답 데이터:", response.data);
  } else {
    console.log("오류 발생:", response.error);
  }
}

2. 폼 입력값의 유효성 검사

function validateInput(input: string | number) {
  if (typeof input === "string") {
    return input.trim().length > 0;
  } else {
    return input > 0;
  }
}


🎯 결론: 언제 타입 가드를 사용해야 할까?

  1. 유니온 타입(A | B)을 사용할 때, 특정 타입으로 좁혀야 하는 경우

  2. API 응답 데이터를 안전하게 처리해야 할 때

  3. 코드의 안전성을 높여야 할 때


타입스크립트에서 타입 가드는 필수적인 개념이고, 이를 활용하면 더욱 안전하고 예측 가능한 코드를 작성할 수 있다는 아주 큰 장점이 있으니 여러 번 나누어 공부해야겠다!

profile
멈추지만 않으면 도착해 🛫

0개의 댓글