타입 가드 완전 정리: 타입 좁히기의 핵심
TypeScript의 진짜 힘은 타입을 안전하게 좁히는 것에 있습니다. 그 중에서는 **타입 가드(type guard)**가 있습니다.
타입 가드는 조건문을 통해
타입을 구체적으로 좁혀주는 문법입니다.
1️⃣ 타입 가드란?
TypeScript는 조건문 앙에서 변수의 타입을 자동으로 좁혀줍니다.
function printId(id: number | string) {
if (typeof id === 'string') {
console.log(id.toUpperCase()); // string으로 좁혀짐
} else {
console.log(is.toFixed(2)); // number로 좁혀짐
}
}
typeof, instanceof, in 같은 표현이 바로 내장 타입 가드입니다.
2️⃣ 대표적인 타입 가드 문법
🔹 typeof
if (typeof value === "string") {
// value는 string
}
string,number,boolean,symbol,undefined,bigint확인 가능
🔹 instanceof
if (error instanceof Error) {
// error는 Error 타입
}
- 클래스를 기준으로 확인
🔹 in 연산자
if ("radius" in shape) {
// shape는 Circle로 추론됨
}
- 객체에 특정 프로퍼티가 존재하는지 확인 → 구별된 유니언에서 자주 사용
🔹 Truthy 체크
if (user) {
// user는 null 또는 undefined가 아님
}
- falsy한 값 제거:
null,undefined,0,'',false등
3️⃣ 사용자 정의 타입 가드 함수
type Cat = { meow: () => void };
type Dog = { bark: () => void };
type Pet = Cat | Dog;
function isCat(pet: Pet): pet is Cat {
return "meow" in pet; // Cat 타입에만 meow 프로퍼티가 존재
}
function speak(pet: Pet) {
if (isCat(pet)) {
pet.meow(); // Cat으로 좁혀짐
} else {
pet.bark(); // Dog
}
}
✔️ retrun value is Type 형식의 핵심
✔️ 조건이 true일 때 Type으로 좁혀주겠다는 의미
4️⃣ 구별된 유니언(discriminated union)
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
}
}
✔️ kind 라는 고유한 속성으로 타입을 정확히 구별할 수 있습니다.