BeginnerCoder

Lesson 6 — Unions & narrowing

Narrowing a union

With a union like string | number, TypeScript only lets you use what both types share. Narrowing means checking which one you have — for example with typeof x === "string" — after which TypeScript knows the exact type inside that branch, and x.length is allowed.

function label(v: string | number) {
  if (typeof v === "number") return v.toFixed(1); // v is number here
  return v.trim();                                 // v is string here
}

Why it matters: narrowing is how you handle "either-or" data safely, without casts or crashes.

Want it another way?
Task

Make size return the length of a string, or the number itself. Expect: 2 42

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.