타입 좁히기

Type narrowing

조건문으로 값의 가능한 타입을 줄여, 분기 안에서 안전하게 해당 타입의 연산을 사용합니다.

···
html
<div class="demo"><div class="head"><strong>TYPE NARROWING</strong><span id="value">value = "atlas"</span></div><div class="scene"><div class="chip" id="check">typeof value</div><span class="arrow">→</span><div class="chip" id="string">string<br>.toUpperCase()</div><div class="chip" id="number">number<br>.toFixed(1)</div></div><div class="foot"><span id="result">result: ATLAS</span><span>tap to switch</span></div></div>
css
.demo{width:min(92vw,660px);height:min(86vh,310px);border:1px solid var(--line);border-radius:14px;background:var(--surface);padding:clamp(10px,2.5vmin,20px);display:flex;flex-direction:column;gap:clamp(6px,1.7vmin,12px);box-shadow:0 10px 35px rgba(0,0,0,.07);font:500 clamp(10px,2.8vmin,15px)/1.35 ui-monospace,SFMono-Regular,Consolas,monospace}
.head,.foot{display:flex;align-items:center;justify-content:space-between;gap:8px}.head strong{color:var(--accent);font-size:1.05em}.foot{color:var(--muted);font-size:.85em;min-height:1.4em}.scene{flex:1;min-height:0;position:relative;display:flex;align-items:center;justify-content:center;gap:clamp(5px,1.5vmin,12px)}.chip{border:1px solid var(--line);background:var(--bg);border-radius:7px;padding:.4em .6em;text-align:center}.on{border-color:var(--accent)!important;background:color-mix(in srgb,var(--accent) 12%,var(--surface))!important;color:var(--accent)!important}.dim{opacity:.42}.arrow{color:var(--muted)}
.scene .chip{min-width:23%;padding:1em .4em}.scene .chip:not(:first-child){height:65%;display:flex;flex-direction:column;justify-content:center}
js
let tick=0;function advance(){const value=tick%2?3.5:"atlas";const kind=typeof value;document.getElementById("value").textContent="value = "+JSON.stringify(value);document.getElementById("string").classList.toggle("on",kind==="string");document.getElementById("number").classList.toggle("on",kind==="number");document.getElementById("result").textContent="result: "+(kind==="string"?value.toUpperCase():value.toFixed(1));tick++}advance();const timer=setInterval(advance,1400);document.querySelector(".demo").addEventListener("pointerdown",()=>{clearInterval(timer);advance()})

유니언 타입 값은 여러 형태 중 하나일 수 있습니다. typeof 같은 검사를 통과하면 타입 검사기는 해당 분기에서 가능한 타입을 좁힙니다.

데모는 같은 변수에 문자열과 숫자를 번갈아 넣습니다. 실제 JavaScript 조건이 각 값의 타입을 검사하고, 문자열에서는 대문자 변환을, 숫자에서는 소수점 포맷을 실행합니다. 분기 밖에서 한쪽 타입 전용 메서드를 호출하면 오류가 날 수 있습니다.

언제 쓰나

API 응답이나 사용자 입력처럼 여러 타입이 들어올 수 있는 값을 안전하게 처리할 때 사용합니다.

페이지로 열기 ↗