Ugrás a fő tartalomra
← ⚡ JavaScript & the browser·Modul C5 · Lecke 2
FeladatWrite format(x) that returns: x.toFixed(2) for numbers, x.toUpperCase() for strings, "yes"/"no" for booleans, "unknown" otherwise. Log format(3.14159), format("hi"), format(true), format(null).

Narrowing with if + typeof

100 XP8 min
Elmélet

What is narrowing

A parameter can arrive as many types. Narrowing is splitting your code into branches per type so each branch only handles ONE shape.

function format(x) {
  if (typeof x === "number") return x.toFixed(2);
  if (typeof x === "string") return x.toUpperCase();
  if (typeof x === "boolean") return x ? "yes" : "no";
  return "unknown";
}

Inside each if branch the value is guaranteed to be that type. Editors with TypeScript-aware tooling (VS Code's JS server, JetBrains) will auto-complete the right methods inside each branch — no .ts file required.

The "fall through" guard

Always end with a default branch that handles "everything else". It's documentation: "I thought about other types, here's what happens."

🔒

Regisztrálj, hogy elkezdj programozni

Az elmélet mindenkinek nyitva. A szerkesztő, élő előnézet és ellenőrzés 7 napos ingyenes próbával nyílik meg — kártya szükséges, bármikor lemondható.

Regisztráció — ingyenes próba →

Minden útvonal első 10 leckéje ingyenes. Nem kell kártya.

← ElőzőKövetkező lecke →

Egy Python- vagy webes tipp naponta — emailben

Rövid, kézzel írt, spam nélkül. Egy kattintással leiratkozhatsz.