Parsing with Template Literals
Extract structured data from strings using infer.
Parsing with Template Literals is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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' }Narrowing Inferred Parts
You can constrain an inferred variable with extends inline, so it only matches certain shapes. Here the method must be a known verb.
type Method = 'GET' | 'POST';
type Parse<S> =
S extends Tpl<(infer M extends Method), ' ', infer P>
? { method: M; path: P }
: never;
// the inferred M is constrained to Method inside the template pattern
type X = Parse<'POST /x'>; // { method: 'POST'; path: '/x' }Parsing Key-Value Pairs
Combine splitting and parsing: split a query string into pairs, then parse each pair into a key and value. The result is a tuple of structured entries.
type Pair<S> =
S extends Tpl<infer K, '=', infer V> ? [K, V] : [S, ''];
// Tpl<K, '=', V> splits a 'key=value' string literal type
type X = Pair<'page=2'>; // ['page', '2']Building an Object From Pairs
Fold a tuple of key-value pairs into an object type using a mapped/intersection accumulator. Each pair adds one property.
type FromPairs<T extends [string, string][]> =
T extends [[infer K extends string, infer V], ...infer R extends [string, string][]]
? { [P in K]: V } & FromPairs<R>
: {};
type X = FromPairs<[["a", "1"], ["b", "2"]]>; // { a: "1" } & { b: "2" }Parsing a Query String
Put it together: split on "&", parse each piece on "=", then build the object. The compiler now knows the exact keys of a query string literal.
type ParseQuery<S extends string> =
FromPairs<{ [I in keyof SplitAmp<S>]: Pair<SplitAmp<S>[I] & string> }>;
// where SplitAmp splits on "&" (from previous lesson)Extracting Numbers
Inferred parts are always string literal types. To treat a part as a number, you check whether it matches a numeric pattern or map it through a digits-only constraint. The value stays a literal type.
type IsNumeric<S extends string> =
S extends Tpl<number> ? true : false;
// Tpl<number> is a template literal type that matches any numeric string
type X = IsNumeric<'42'>; // true
type Y = IsNumeric<'4a'>; // falseOptional Segments
Use a union of patterns to handle optional parts. Try the richer pattern first; fall back to the simpler one if it does not match.
type ParsePath<S> =
S extends Tpl<infer Base, '?', infer Query>
? { base: Base; query: Query }
: { base: S; query: '' };
// Tpl<Base, '?', Query> matches an optional query after a question mark
type X = ParsePath<'/x?a=1'>; // { base: '/x'; query: 'a=1' }Whitespace and Edge Cases
Real strings have stray spaces. Compose your parser with Trim from the previous lesson so leading and trailing whitespace does not corrupt the extracted fields.
type CleanKey<S extends string> = Trim<S>;
// Apply Trim to each inferred segment before using itWhy This Is Powerful
Template-literal parsing lets the compiler understand formats: dates, routes, env keys, SQL fragments. Mistyped strings become compile errors, and downstream types can depend on the parsed structure. The string literal becomes a typed value.
type Event<S> =
S extends Tpl<infer Domain, ':', infer Action>
? { domain: Domain; action: Action }
: never;
// Tpl<Domain, ':', Action> matches 'domain:action'
type X = Event<'user:created'>; // { domain: 'user'; action: 'created' }Composing Parsers
Just like value-level combinators, type-level parsers compose. Split, then parse each part, then assemble an object. Each step is a small conditional type, and together they form a complete, typed parser.
// Split -> Pair -> FromPairs is a parser pipeline at the type levelQuick Check
Test your understanding of template-literal parsing.
Recap
You extracted structured data from string types.
- Multiple
inferpoints capture named fields in one pattern. - Inferred parts can be narrowed with inline
extends. - Split, Pair, and FromPairs compose into a query parser.
- Trim and numeric checks handle edge cases.
Next: a complete mini route parser.
Frequently asked questions
Is the “Parsing with Template Literals” lesson free?
Yes — the full text of “Parsing with Template Literals” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Parsing with Template Literals”?
Extract structured data from strings using infer. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Parsing with Template Literals” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Parser Combinator Concepts
- Type-Level String Splitting
- Parsing with Template Literals
- A Mini Type-Level Route Parser