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 leftoverA 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
- Parser Combinator Concepts
- Type-Level String Splitting
- Parsing with Template Literals
- A Mini Type-Level Route Parser