TypeScript Intermediate: Utility Types, Narrowing & Advanced Types

Lesson 2 of 7

Type Narrowing: unknown, Guards & Predicates

Not every value flowing through a program has a known type up front, JSON parsed from a network response, user input, data from a library without types. TypeScript gives you unknown for exactly that, plus tools to narrow it down safely.

TypeScript

unknown vs any

any turns off type checking entirely, unknown still forces you to prove what a value is before you can use it.

TypeScript

unknown is the type-safe way to accept "could be anything," it makes the compiler force every caller to check before touching the value, any just gets out of the way and hopes for the best.

Narrowing with typeof, instanceof, and in

TypeScript

Custom type predicates

For shapes typeof/instanceof/in can't fully describe, write your own narrowing function with an is return type.

TypeScript

value is Task tells the compiler: "if this function returns true, treat value as a Task from this point on." It's not checked for correctness, a wrong isTask will lie to the compiler, so the logic inside still has to be right.

WARNING

Reach for unknown, not any, whenever a value's type genuinely isn't known yet (parsed JSON, a library return value). any is easy in the moment but silently reintroduces every bug static types exist to prevent.

📝 Narrowing Quiz

Passing score: 70%
  1. 1.What's the key difference between unknown and any?

  2. 2.A function with return type 'value is Task' is a custom type predicate.

  3. 3.The operator used to narrow a union by checking whether a property exists on an object is ____.

  4. 4.Which keyword narrows a union to a specific class instance?

  5. 5.A custom type predicate is checked for logical correctness by the compiler, so a wrong one is impossible to write.