Skip to content

Type Narrowing

The Course
•
25 min study

Narrowing is how the checker uses conditions to refine a type. If a parameter starts as string | number, then inside typeof value === "string" it can be treated as string. In the other branch it is number. The condition runs at runtime too; it is evidence, not a promise pasted onto a value.

typeof is the JavaScript operator that returns a text label such as "string" or "number". toFixed(1), used in the exercise, formats a number with one digit after the decimal point and returns a string: 2 becomes "2.0". It does not change the original number.

Use operations supported by the current narrowed type. Outside the branch, only operations valid for the whole union are safe. Do not call a string method just because one of the possible types has it.

Objects can carry a discriminant: a common field with a different literal value for each variant. A result could be { kind: "ok"; minutes: number } or { kind: "error"; message: string }. Checking kind tells both JavaScript and TypeScript which other fields are present. This is called a discriminated union.

Keep variant-specific data inside its variant. A single record with optional minutes and optional message permits confusing combinations: both missing or both supplied. Two explicit shapes represent the intended alternatives more clearly.

The result below is an ordinary object returned immediately by a function. It describes success or failure as data for the caller to inspect, instead of throwing an exception. You already know if/else, so you can use it immediately. Later validation lessons will return this kind of result for messy data.

Predict, check, then run

Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.

Predict, then runTypeScript
type Result =
  | {
      kind: "ok";

      minutes: number;
    }
  | {
      kind: "error";

      message: string;
    };

function describe(result: Result): string {
  if (result.kind === "ok") {
    return `${result.minutes} min`;
  }

  return result.message;
}

console.log(describe({ kind: "ok", minutes: 20 }));
console.log(describe({ kind: "error", message: "Try again" }));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
20 min
Try again

Read a real compiler error

Even though this particular call uses text, the function promises to accept numbers too.

Find and fix the type errorTypeScript
function display(value: string | number): string {
  return value.trim();
}

console.log(display(" Types "));

Enable JavaScript to edit and type-check this example.

Check your diagnosis

The body must be safe for every accepted input. Narrow with typeof before trim, and supply behavior for numbers. Changing only the demonstration call does not fix the contract.

Let the discriminant select the available data

A tagged union keeps each outcome paired with its fields. Checking the tag is evidence about the whole record, not just about one string property. Keep that relationship intact until you have selected the branch that owns the data you want.

A boolean truthiness test is often weaker than a discriminant check. A successful result can contain zero or empty text. Model success explicitly so those meaningful values do not accidentally become errors in the formatter.

Let the discriminant select the available data: traceTypeScript
type Result =
  | {
      kind: "ok";

      value: number;
    }
  | {
      kind: "error";

      message: string;
    };

function label(result: Result): string {
  if (result.kind === "ok") {
    return String(result.value);
  }

  return result.message;
}

console.log(label({ kind: "ok", value: 0 }));
console.log(label({ kind: "error", message: "Try again" }));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
0
Try again

Zero remains a success because kind decides the branch. Checking result.value truthiness would not express the outcome and is not valid on the error member anyway.

Let the discriminant select the available data: contrastTypeScript
function count(value: string | number): number {
  if (typeof value === "string") {
    return value.length;
  }

  return value;
}

console.log(count("Types"));
console.log(count(0));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
5
0

After the string branch returns, only number remains. Narrowing can follow early returns; it does not require deeply nested if blocks.

Try the rule on new inputs

Add another result example with an empty successful string in a separate string-valued union. Explain how its tag preserves success. Then remove a narrowing check and read the property-access error rather than casting it away.

Debug a plausible mistake

Exercise

Repair a union operation

show should print the minutes of a successful result and the message of a failed one. Zero minutes is a real success. Print 0 min then Blank. Keep the Result union as it is.

Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.

Find and fix the type errorTypeScript
type Result =
  | { kind: "ok"; minutes: number }
  | { kind: "error"; message: string };

function show(result: Result): string {
  if (result.minutes > 0) {
    return `${result.minutes} min`;
  }
  return result.message;
}

console.log(show({ kind: "ok", minutes: 0 }));
console.log(show({ kind: "error", message: "Blank" }));

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Read which member of the union the diagnostic says lacks minutes. Only one field tells you which member you have.

Hint 2: a first step

Replace the condition with a test of the kind field, then check what the first call should print.

Show one solution
TypeScript
type Result =
  | { kind: "ok"; minutes: number }
  | { kind: "error"; message: string };

function show(result: Result): string {
  if (result.kind === "ok") {
    return `${result.minutes} min`;
  }
  return result.message;
}

console.log(show({ kind: "ok", minutes: 0 }));
console.log(show({ kind: "error", message: "Blank" }));
Text
0 min
Blank

TS2339 said minutes does not exist on the error member, so result.minutes can't be read until the kind is known. Checking kind === "ok" narrows to the success member in the if branch and to the error member after it. It also fixes a hidden bug: minutes > 0 would have sent the zero-minute success down the message path.

Your turn

Exercise

Type Narrowing: practice

A duration arrives either in minutes or in hours. Define a discriminated union Duration with a unit field: { unit: "minutes"; minutes: number } or { unit: "hours"; hours: number }. Write toMinutes(duration: Duration): number, then print 45 for 45 minutes and 90 for 1.5 hours.

Your workspaceTypeScript
// Define Duration, write toMinutes, and test one value of each shape.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Here the evidence is a field, not typeof: both members are objects, so typeof would say "object" for each.

Hint 2: a first step

Write the two object shapes joined by |, then begin toMinutes with a branch testing the unit field.

Show one solution
One possible solutionTypeScript
type Duration =
  | { unit: "minutes"; minutes: number }
  | { unit: "hours"; hours: number };

function toMinutes(duration: Duration): number {
  if (duration.unit === "hours") {
    return duration.hours * 60;
  }

  return duration.minutes;
}

console.log(toMinutes({ unit: "minutes", minutes: 45 }));
console.log(toMinutes({ unit: "hours", hours: 1.5 }));

Enable JavaScript to edit and type-check this example.

Text
45
90

unit is the discriminant: inside the "hours" branch the checker knows duration.hours exists, and after that branch returns only the minutes member is left. Writing { unit: "hours", minutes: 90 } would be rejected, because no member pairs that unit with that field. That is the advantage over one record with two optional numbers.

Change it and explain it

Add a boolean alternative and give it an explicit branch. Explain why a cast would not convert a boolean to a number. Then draw the two Result shapes from the example and identify their discriminant.

Was this article helpful?

Your response is saved on this device.