Lesson 2.4

infer and type-level pattern matching

Inside a conditional, infer introduces a type variable bound to whatever matched.

19mIntermediate17.4k students

Overview

Pulling a type back out

Inside a conditional, infer introduces a type variable bound to whatever matched. That is how you get an array element type, a promise resolution type, or the parameters of a function without the caller passing them.

Template literal types extend this to strings: a route pattern can be matched against and its parameters extracted, so a router knows the shape of its own params object.

There is a ceiling. Deeply recursive type-level code slows the compiler and produces error messages nobody can read. When a type takes longer to understand than the bug it prevents, it is no longer paying for itself.

In this lesson you will:

  • Extract a piece of a type with infer
  • Parse a string type with template literals
  • Know when type-level cleverness costs too much

Resources

Previous Lesson
Next Lesson
infer and type-level pattern matching — TypeScript Deep Dive — Vertex