0Pricing
TypeScript Academy · Lesson

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'>; // false

Inferring 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

  1. Parser Combinator Concepts
  2. Type-Level String Splitting
  3. Parsing with Template Literals
  4. A Mini Type-Level Route Parser
← Back to TypeScript Academy