devShark · Quick guide

TypeScript narrowing fundamentals

Runtime checks such as typeof, in, discriminants and predicates refine a broad static type inside a controlled branch.

How it works

A union describes several possible values, while the typeof check gives TypeScript evidence about the value in this branch; checking a tag on an object works in the same way, but casting untrusted JSON with as only changes what the compiler assumes and cannot replace runtime validation.

function label(value: string | number) {
  if (typeof value === "string") {
    return value.trim();
  }
  return value.toFixed(2);
}
Read the documentation

Common misconception

A type assertion does not validate data at runtime.

Quick practice

1. Which operator narrows primitives?

typeof

2. What identifies a discriminated union member?

A shared literal tag.

3. Does `as` validate input?

No.

Practice in a quiz

More guides