Type-Level String Splitting
Split strings into tuples within the type system.
Template Literal Types
The type system can pattern-match on string literal types using template literal types combined with infer. This is the core tool for type-level string parsing.
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 StartsWithA<S> = S extends Tpl<'a', string> ? true : false;
// Tpl<'a', string> is a backtick template literal type: 'a' then anything
type X = StartsWithA<'abc'>; // true
type Y = StartsWithA<'bcd'>; // falseInferring a Suffix
Place infer inside the template to capture part of the string. Here we capture everything after a leading "a".
type AfterA<S> = S extends Tpl<'a', infer Rest> ? Rest : never;
// Tpl<'a', Rest> captures everything after a leading 'a'
type X = AfterA<'abc'>; // 'bc'All lessons in this course
- Parser Combinator Concepts
- Type-Level String Splitting
- Parsing with Template Literals
- A Mini Type-Level Route Parser