0Pricing
TypeScript Academy · Lesson

Parsing with Template Literals

Extract structured data from strings using infer.

From Splitting to Structure

Splitting gives a tuple of parts. Parsing goes further: it extracts named, structured data from a string type. We use template literal patterns with multiple infer variables to pull out the pieces we care about.

Notation: real TypeScript writes template literal types with backtick-delimited strings containing dollar-brace holes. In these snippets we show that pattern as Tpl<...>, listing each part in order; e.g. a backtick template matching the literal prefix then Rest appears as Tpl<'prefix', infer Rest>.

type KeyValue<S> =
  S extends Tpl<infer K, '=', infer V> ? { key: K; value: V } : never;
// Tpl<K, '=', V> matches K, an equals sign, then V

type X = KeyValue<'name=alice'>; // { key: 'name'; value: 'alice' }

Multiple Inference Points

A single pattern can capture several fields at once. To parse "GET /users", infer the method and the path in one conditional.

type Request<S> =
  S extends Tpl<infer Method, ' ', infer Path>
    ? { method: Method; path: Path }
    : never;
// Tpl<Method, ' ', Path> matches the method, a space, then the path

type X = Request<'GET /users'>; // { method: 'GET'; path: '/users' }

All lessons in this course

  1. Parser Combinator Concepts
  2. Type-Level String Splitting
  3. Parsing with Template Literals
  4. A Mini Type-Level Route Parser
← Back to TypeScript Academy