0Pricing
TypeScript Academy · Lesson

Parser Combinator Concepts

Compose small parsers into larger ones.

What Is a Parser

A parser reads input (usually a string) and produces structured output, or fails. We start at the value level to build intuition before moving the same ideas into the type system.

type Parser<T> = (input: string) => { value: T; rest: string } | null;
// Consumes part of the input, returns a value and the leftover

A Tiny Parser

The simplest parser matches a literal prefix. If the input starts with the expected text, it succeeds and returns the remaining string; otherwise it returns null.

function literal(prefix: string): Parser<string> {
  return input =>
    input.startsWith(prefix)
      ? { value: prefix, rest: input.slice(prefix.length) }
      : null;
}
console.log(literal("ab")("abc"));

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