Search

Search through articles and snippets by title, tags, or content.

Back to Snippets
TypeScript
Feb 10, 2026

Type Guard로 안전한 타입 좁히기

사용자 정의 타입 가드를 사용하여 유니온 타입을 안전하게 좁히는 패턴입니다.

TypeScriptType SafetyPattern

Type Guard 함수

유니온 타입을 다룰 때 is 키워드로 타입 가드를 만들면, 조건 분기 후 타입이 자동으로 좁혀집니다.

type-guard.ts
interface ApiSuccess<T> {
  status: "success";
  data: T;
}
 
interface ApiError {
  status: "error";
  message: string;
  code: number;
}
 
type ApiResponse<T> = ApiSuccess<T> | ApiError;
 
// 타입 가드 함수
function isApiError<T>(res: ApiResponse<T>): res is ApiError {
  return res.status === "error";
}
 
// 사용 예시
async function fetchUser(id: string) {
  const res: ApiResponse<User> = await api.get(`/users/${id}`);
 
  if (isApiError(res)) {
    // res는 ApiError 타입으로 좁혀짐
    console.error(`Error ${res.code}: ${res.message}`);
    return null;
  }
 
  // res는 ApiSuccess<User> 타입으로 좁혀짐
  return res.data;
}

배열 필터에서의 활용

filter와 함께 사용하면 undefined를 안전하게 제거할 수 있습니다.

filter-guard.ts
function isDefined<T>(value: T | undefined | null): value is T {
  return value != null;
}
 
const items = [1, undefined, 3, null, 5];
const defined = items.filter(isDefined);
// defined: number[] (undefined | null 제거됨)