Skip to content

Type-level parsing with template literals

Relay subscribers filter webhooks with a small string: source == github && event in (push, pull). A subscriber wrote sorce == github. It parsed, matched nothing, and the subscriber got no events for a week. The filter is a string, so the compiler sees nothing. If the string is a literal, though, the compiler can read it.

Template literal types already split "/hooks/:source/:id" with one infer per slot. A filter has a grammar: operators, lists, a conjunction. This lesson builds the parts a real parser needs as types: a tokenizer, parser state, an AST, and errors that read well. At the end it also shows where the checker stops.

A slot in a template literal pattern can hold a union. The pattern then matches if any member matches:

type Space = " " | "\n" | "\t"
type TrimLeft<S extends string> = S extends `${Space}${infer R}` ? TrimLeft<R> : S
type TrimRight<S extends string> = S extends `${infer R}${Space}` ? TrimRight<R> : S
type Trim<S extends string> = TrimLeft<TrimRight<S>>
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Trimmed = Expect<Equal<Trim<" event in (push)\n ">, "event in (push)">>

TrimRight puts infer R first and the union last, so it matches a string that ends in any of the three characters and removes one per step. Every type-level parser needs this first, because spacing is never part of the grammar.

${infer C}${infer Rest} is the tool for walking a string: C is exactly the first character, because infer captures the shortest match and a slot followed directly by another slot gets one character. To decide whether a character belongs to an identifier, test it against a union of the allowed characters:

type Lower =
| "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m"
| "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
type IdentChar = Lower | Uppercase<Lower> | Digit | "_"
type TakeIdent<S extends string, Acc extends string = ""> = S extends `${infer C}${infer Rest}`
? C extends IdentChar
? TakeIdent<Rest, `${Acc}${C}`>
: [Acc, S]
: [Acc, S]
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Word = Expect<Equal<TakeIdent<"push, pull)">, ["push", ", pull)"]>>
export type Nothing = Expect<Equal<TakeIdent<"== github">, ["", "== github"]>>

TakeIdent returns a pair: the identifier it consumed and the rest of the input. That pair shape is the whole design of the parser: every step takes input and returns [result, rest]. The accumulator Acc grows one character at a time, and the recursive call is the last thing in each branch, which makes it a tail call (more in the last section).

Why a union of characters and not a regular expression? Types have no regular expressions. A char union is the type-level character class, and C extends IdentChar is a plain assignability check on one-character strings.

TypeScript 4.8 added extends constraints to infer in a template literal. If the captured text is a valid, canonical number, the type is the number literal:

type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
type ToNumber<S extends string> = S extends `${infer N extends number}` ? N : never
export type Port = Expect<Equal<ToNumber<"8080">, 8080>>
export type Negative = Expect<Equal<ToNumber<"-7">, -7>>
export type Fraction = Expect<Equal<ToNumber<"4.5">, 4.5>>
export type Padded = Expect<Equal<ToNumber<"042">, number>>
export type Exponent = Expect<Equal<ToNumber<"1e3">, number>>
export type Word = Expect<Equal<ToNumber<"abc">, never>>
type ToBoolean<S extends string> = S extends `${infer B extends boolean}` ? B : never
export type Yes = Expect<Equal<ToBoolean<"true">, true>>
export type No = Expect<Equal<ToBoolean<"false">, false>>

The rule is a round trip: the literal is used only if converting the number back to a string gives the same text. "042" and "1e3" do not round-trip, so the result falls back to number. Text that is not numeric fails the match. boolean works the same way. A Relay filter like attempts == 3 can produce the number 3 in the AST this way. Use it for canonical numbers only, and never treat the number fallback as success.

Parsing splits into two passes. A tokenizer turns text into tokens and a parser turns tokens into a tree. Each pass is smaller than a one-pass parser, and errors come from the layer that understands them.

type Space = " " | "\n" | "\t"
type Lower =
| "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m"
| "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
type IdentChar = Lower | Uppercase<Lower> | Digit | "_"
type TakeIdent<S extends string, Acc extends string = ""> = S extends `${infer C}${infer Rest}`
? C extends IdentChar
? TakeIdent<Rest, `${Acc}${C}`>
: [Acc, S]
: [Acc, S]
type Token = "==" | "&&" | "(" | ")" | "," | { readonly id: string }
type Tokenize<S extends string, Out extends Token[] = []> = S extends `${Space}${infer R}`
? Tokenize<R, Out>
: S extends `==${infer R}`
? Tokenize<R, [...Out, "=="]>
: S extends `&&${infer R}`
? Tokenize<R, [...Out, "&&"]>
: S extends `(${infer R}`
? Tokenize<R, [...Out, "("]>
: S extends `)${infer R}`
? Tokenize<R, [...Out, ")"]>
: S extends `,${infer R}`
? Tokenize<R, [...Out, ","]>
: S extends ""
? Out
: TakeIdent<S> extends [infer Id extends string, infer R extends string]
? Id extends ""
? "unexpected character"
: Tokenize<R, [...Out, { readonly id: Id }]>
: never
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Tokens = Expect<
Equal<
Tokenize<"source == github && event in (push, pull)">,
[
{ readonly id: "source" },
"==",
{ readonly id: "github" },
"&&",
{ readonly id: "event" },
{ readonly id: "in" },
"(",
{ readonly id: "push" },
",",
{ readonly id: "pull" },
")",
]
>
>

Two details. Identifier tokens are objects ({ id: "push" }) so the parser can tell the word in from an operator without reserved-word tricks. And the output is a tuple that grows with each token. A tuple is how type-level code keeps state: you cannot mutate a type, so each step returns a new tuple from [...Out, token].

The parser reads one condition from the front of the token tuple and returns the condition and the tokens left over. Tuple patterns with a rest element do the destructuring:

type Token = "==" | "&&" | "(" | ")" | "," | { readonly id: string }
type ParseList<T extends Token[], F extends string, Acc extends string[] = []> = T extends [
{ readonly id: infer V extends string },
")",
...infer Rest extends Token[],
]
? [{ readonly op: "in"; readonly field: F; readonly values: [...Acc, V] }, Rest]
: T extends [{ readonly id: infer V extends string }, ",", ...infer Rest extends Token[]]
? ParseList<Rest, F, [...Acc, V]>
: never
type ParseCond<T extends Token[]> = T extends [
{ readonly id: infer F extends string },
"==",
{ readonly id: infer V extends string },
...infer Rest extends Token[],
]
? [{ readonly op: "eq"; readonly field: F; readonly value: V }, Rest]
: T extends [{ readonly id: infer F extends string }, { readonly id: "in" }, "(", ...infer Rest extends Token[]]
? ParseList<Rest, F>
: never
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type One = Expect<
Equal<
ParseCond<[{ readonly id: "event" }, { readonly id: "in" }, "(", { readonly id: "push" }, ",", { readonly id: "pull" }, ")", "&&"]>,
[{ readonly op: "in"; readonly field: "event"; readonly values: ["push", "pull"] }, ["&&"]]
>
>

ParseCond is a grammar rule written as a tuple pattern. ParseList is a loop: the accumulator Acc collects values until it meets ). A loop over && on top of ParseCond gives the whole filter, and the exercise has you write it. The result is the AST: a tuple of conditions with the exact strings in it, so values is ["push", "pull"] and not string[].

The AST pays off when you use it. The fields a filter mentions are Ast[number]["field"], and a function can demand exactly those fields on the event it is applied to:

type Condition =
| { readonly op: "eq"; readonly field: string; readonly value: string }
| { readonly op: "in"; readonly field: string; readonly values: readonly string[] }
type Fields<A extends readonly Condition[]> = A[number]["field"]
type FilterInput<A extends readonly Condition[]> = { [K in Fields<A>]: string }
type Ast = [
{ readonly op: "eq"; readonly field: "source"; readonly value: "github" },
{ readonly op: "in"; readonly field: "event"; readonly values: ["push", "pull"] },
]
declare function filterBy(event: FilterInput<Ast>): boolean
filterBy({ source: "github", event: "push" })
// @ts-expect-error: the filter reads event, so the event must have it
filterBy({ source: "github" })

When parsing fails, never tells the caller nothing. Return a type that carries a message. A string literal intersected with a brand reads well in hovers and cannot be mistaken for a real result:

interface ParseErrorBrand {
readonly __brand: "ParseError"
}
type ParseError<M extends string> = `ParseError: ${M}` & ParseErrorBrand
type Check<T> = T extends ParseErrorBrand ? "error" : "ok"
declare const bad: ParseError<"expected '&&' or the end of the filter">
const message: `ParseError: ${string}` = bad
// @ts-expect-error: an error is not a Condition list
const ast: readonly { op: string }[] = bad
const kind: Check<typeof bad> = "error"
console.log(message, ast, kind)

The brand is what the parser tests for (T extends ParseErrorBrand). The template string is what you read: hover a bad filter and the editor shows ParseError<"expected 'field == value' or 'field in (a, b)'">, with the alias name kept.

Where the error shows up matters. A function whose return type is the parse result becomes uncallable when the filter is bad, and the message is in the type:

interface ParseErrorBrand {
readonly __brand: "ParseError"
}
type ParseError<M extends string> = `ParseError: ${M}` & ParseErrorBrand
type Compiled<S extends string> = S extends `${string}==` ? ParseError<"missing value after '=='"> : (event: object) => boolean
declare function compile<S extends string>(source: S): Compiled<S>
compile("source == github")({})
// @ts-expect-error: the result is an error type, not a function
compile("source ==")({})

The error appears at the call that uses the result, not at the string. That is a limit of the technique: a type cannot put a squiggle under the exact character that is wrong.

Three limits show up in parsers.

Recursion depth. A recursive conditional type that builds its result after the recursive call ([C, ...Chars<R>]) nests one instantiation inside another. With TypeScript 7.0.2 and 5.9.3 a string of 40 characters is fine and one of 60 is rejected, around 50 characters:

type Chars<S extends string> = S extends `${infer C}${infer R}` ? [C, ...Chars<R>] : []
const ok: Chars<"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb">["length"] = 40
// @ts-expect-error: Type instantiation is excessively deep and possibly infinite
const tooDeep: Chars<"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">["length"] = 60

Tail position. If the recursive call is the whole result of its branch and the state travels in an accumulator, the compiler loops instead of nesting. TakeIdent and Tokenize are written that way. The same job with an accumulator handles a string of 900 characters:

type Rep<S extends string, N extends number, Acc extends string = "", C extends unknown[] = []> =
C["length"] extends N ? Acc : Rep<S, N, `${Acc}${S}`, [...C, unknown]>
type CharsTail<S extends string, Acc extends string[] = []> = S extends `${infer C}${infer R}`
? CharsTail<R, [...Acc, C]>
: Acc
const long: CharsTail<Rep<"a", 900>>["length"] = 900

The limit for tail calls is a thousand iterations, not fifty levels. Lesson 7 measures both and shows how to restructure a type that hits them. A tokenizer over a Relay filter, a line of text, never gets near it. A parser for a whole file would.

Union explosion. A slot that holds a union multiplies. Two letters, upper and lower case, make 52 x 52 = 2,704 strings, which is fine. Three make 140,608 and the compiler refuses to build the union:

type Lower =
| "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m"
| "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
type Letter = Lower | Uppercase<Lower>
type Two = `${Letter}${Letter}`
// @ts-expect-error: Expression produces a union type that is too complex to represent
type Three = `${Letter}${Letter}${Letter}`

That is why IdentChar is used to test one character at a time with C extends IdentChar and never to generate strings. A character class is for checking, not for enumerating.

The starter gives you Tokenize and the AST types. Write the parser (ParseCond, ParseList, ParseAll), derive ParseFilter, FilterInput and CompiledFilter, then write the runtime twin parseFilter and compileFilter. The type tests check the AST and the error cases, and the runtime tests check the same inputs against the real parser.

  • A union in a template slot is a character class: C extends IdentChar tests one character, and TrimRight strips any of several characters.
  • infer C followed by infer Rest walks a string one character at a time.
  • infer N extends number gives a number literal only for canonical numbers ("042" stays number).
  • Parse in two passes, text to tokens and tokens to a tree. Carry state in tuples and return [result, rest].
  • Report errors with a branded message type. It shows in hovers, but the error appears where the result is used.
  • Non-tail recursion fails near 50 levels. Accumulators make a tail call, good for about a thousand iterations (7.0.2 and 5.9.3). Char-union templates multiply: 52 x 52 x 52 members is already too many.
  • Use type-level parsing for small literal DSLs. Parse runtime input at runtime.