Перейти к основному содержимому
← ⚡ JavaScript & the browser·Модуль C5 · Урок 2
ЗаданиеWrite 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
Теория

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."

🔒

Зарегистрируйся чтобы кодить

Теория открыта всем. Интерактивный редактор, живой превью и проверка открываются с 7-дневным бесплатным trial — нужна карта, отмена в любое время.

Регистрация — бесплатный trial →

Первые 10 уроков в каждом треке — бесплатные. Карта не нужна.

← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.