TypeScript 타입 내로잉 완벽 가이드
0회 조회
TypeScript 타입 내로잉 완벽 가이드
타입 내로잉(Type Narrowing)은 유니온 타입을 더 구체적인 타입으로 좁히는 과정입니다.
typeof 가드
function format(value: string | number): string {
if (typeof value === 'string') {
return value.toUpperCase() // string
}
return value.toFixed(2) // number
}
instanceof 가드
function processError(error: Error | string) {
if (error instanceof Error) {
console.error(error.message) // Error 타입
} else {
console.error(error) // string 타입
}
}
in 연산자
interface Dog { bark(): void }
interface Cat { meow(): void }
function makeSound(animal: Dog | Cat) {
if ('bark' in animal) {
animal.bark() // Dog
} else {
animal.meow() // Cat
}
}
판별 유니온 (Discriminated Union)
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'rectangle'; width: number; height: number }
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2
case 'square':
return shape.side ** 2
case 'rectangle':
return shape.width * shape.height
}
}
판별 유니온은 switch 문과 함께 사용할 때 **완전성 검사(exhaustiveness check)**가 가능합니다.
사용자 정의 타입 가드
interface User {
id: number
name: string
}
function isUser(value: unknown): value is User {
return (
typeof value === 'object' &&
value !== null &&
'id' in value &&
'name' in value
)
}
const data = JSON.parse(response)
if (isUser(data)) {
console.log(data.name) // User 타입으로 안전하게 사용
}
타입 내로잉을 잘 활용하면 런타임 오류를 컴파일 타임에 잡을 수 있습니다.