Type-Level JSON Parsing
February 9, 20261 min readpart 20/20
Difficulty: Expert. Prerequisites: All previous topics — this is the capstone.
Type-level JSON parsing is the ultimate test of TypeScript's type system. It involves parsing JSON string literals into TypeScript types at compile time. While primarily academic, it demonstrates mastery of all advanced type features.
Key concepts
- Type-level tokenization
- Recursive descent parsing patterns
- Building towards nested structure support
- Type-level state machines
Example
// Simplified JSON Parser (no nesting, arrays, or numbers — see exercises for full version)
type Trim<S> = S extends ` ${infer R}` | `\n${infer R}` ? Trim<R> : S;
type ParseString<S> = S extends `"${infer C}"${infer R}` ? [C, R] : never;
type ParseLiteral<S> = S extends `true${infer R}` ? [true, R]
: S extends `false${infer R}` ? [false, R]
: S extends `null${infer R}` ? [null, R] : never;
type ParseValue<S> = Trim<S> extends `"${string}` ? ParseString<Trim<S>>
: Trim<S> extends `{${string}` ? ParseObject<Trim<S>>
: ParseLiteral<Trim<S>>;
type ParseObject<S> = S extends `{${infer C}}${infer R}` ? [ParsePairs<C>, R] : never;
type ParsePairs<S, Acc = {}> = Trim<S> extends ''
? Acc
: Trim<S> extends `"${infer K}":${infer After}`
? ParseValue<After> extends [infer V, infer R]
? Trim<R> extends `,${infer Next}`
? ParsePairs<Next, Acc & { [P in K]: V }>
: Acc & { [P in K]: V }
: Acc
: Acc;
type ParseJSON<S extends string> = ParseValue<S> extends [infer R, any] ? R : never;
// Usage!
type Parsed = ParseJSON<'{"name": "Alice", "active": true}'>;
// { name: "Alice" } & { active: true }
// Real-world: jamiebuilds/json-parser-in-typescript — full parser with arrays, numbers, nestingResources
- Type Challenges - JSON Parser: The ultimate challenge
- HotScript: Type-level parsing utilities
Practice
- JSON Parser (TypeHero, Extreme)
- JSON Parser (Type Challenges, Extreme)
- Query String Parser (Type Challenges, Extreme)
- Object From Entries (Type Challenges, Hard)
- Number Range (Type Challenges, Medium)
- Build a SQL Parser (ts-sql) (ts-sql, Extreme)
Hints
- Start by implementing parsers for individual values (strings, booleans, null), then combine them.
- Use recursive descent parsing — each parser returns the parsed value and the remaining string.