Narrowing은 TypeScript가 런타임 검사를 바탕으로 코드 분기 안에서 넓은 타입(예: union)을 더 구체적인 타입으로 정제하는 방식입니다. 컴파일러는 제어 흐름을 추적하며 그에 따라 타입을 갱신합니다.
ts
() {
( x === ) {
x.();
} {
x.();
}
}
typeof x === "string" // typeof 가드 — 원시 타입용
x instanceof Date // instanceof — 클래스용
"role" in obj // in 연산자 — 프로퍼티 존재 여부
Array.isArray(x) // 내장 가드
if (x) { ... } // truthiness로 null/undefined/0/""를 걸러냄
if (x === null) { ... } // 동등성 narrowing
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; side: number };
function area(s: Shape) {
switch (s.kind) { // 판별자(discriminant)
case "circle": return Math.PI * s.r ** 2; // s는 circle 변형
case "square": return s.side ** 2; // s는 square 변형
}
}
공유된 리터럴 필드(kind)를 검사하면 컴파일러는 어떤 변형인지 정확히 알게 되어 해당 변형의 프로퍼티를 열어줍니다.
function isUser(x: unknown): x is User { return !!x && typeof (x as any).name === "string"; }
Narrowing은 union 타입을 사용 가능하게 만드는 핵심입니다. 타입을 증명한 뒤에만 타입별 멤버에 안전하게 접근하게 하여, 런타임 검사를 컴파일 타임 보증으로 바꿉니다.
string | number, T | null, 태그된 상태를 다루는 일상적인 메커니즘입니다.
주니어부터 시니어까지 상세한 답변이 포함된 IT 면접 질문 라이브러리.
후원하기