Type narrowing

타입 좁히기

A condition reduces the possible types of a value, letting each branch use operations valid for that type.

···
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()})

A union-typed value may have several shapes. A check such as typeof narrows the possible type within a branch.

The demo alternates a string and a number in one variable. A real JavaScript check runs uppercase conversion for the string and decimal formatting for the number. Calling a type-specific method outside the checked branch can fail.

When to use

Use narrowing when handling values that may have different types, such as API responses or user input.

Open as page ↗