AI Hints
TypeScript · Lesson 31 of 120

Narrowing with typeof

Check, then use.

⏱ 2 min read▶ Video at 24:37🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Narrowing means checking a union's type, so TypeScript knows exactly what you have. After the check, inside that branch, you can use everything that type offers.

Narrowing with typeof
From the video: Narrowing with typeof
  • Check the type
  • TypeScript follows
  • Use it fully

typeof narrows

If order ref is a string, we upper case it. Otherwise, it must be a number, so we pad it to six digits. TypeScript follows each branch. Run it.

app.tstypescript
function format(orderRef: number | string): string {
  if (typeof orderRef === "string") {
    return orderRef.toUpperCase();
  }
  return String(orderRef).padStart(6, "0");
}

console.log(format("nw-1042"));
console.log(format(1042));
Output
NW-1042
001042

typeof checks

Typeof works for the basic types. String, number, boolean, undefined, function, and object. For objects and classes, we'll use other checks soon.

keyvalue
"string"text
"number"numbers
"boolean"true/false
"object"objects, arrays, null

Summary

Typeof checks narrow a union to one type inside each branch. Next, truthiness and equality.

Key takeaways
  • typeof x === 'string'
  • Branches
  • Narrowed
Next up: Truthiness and Equality — more narrowing