Course contentsShow
← TypeScript
Lesson 1471 of 1,79633. Inference Inversion PatternsFree lesson

Type-Level String Manipulation

Parsing and transforming string literal types recursively with template literals and infer.

Type-Level String Manipulation

What you'll learn: How to parse and transform string literal types recursively using template literals and infer to create powerful type-level string operations.

You now have all the tools to perform computation on string types at compile time—just as you would parse and manipulate strings at runtime with JavaScript, you can do the same at the type level using TypeScript's type system.

The Core Pattern: Recursive Parsing with infer

Type-level string manipulation combines three key concepts you've learned:

  1. Template literal types to pattern-match string shapes
  2. infer to extract parts of strings
  3. Recursion to process strings character-by-character or segment-by-segment

Think of it like writing a parser: you match the beginning of a string, extract what you need with infer, transform it, and recursively process the rest.

How It Works

The fundamental pattern looks like this:

type ProcessString<S extends string> = 
  S extends `${infer First}${infer Rest}`
    ? /* transform First, recurse on Rest */
    : /* base case when string is empty */;

This is analogous to processing a linked list: you extract the head, operate on it, and recurse on the tail.

Practical Example: String Reversal

type ReverseString<S extends string, Acc extends string = ''> = 
  S extends `${infer First}${infer Rest}`
    ? ReverseString<Rest, `${First}${Acc}`>
    : Acc;

type Result = ReverseString<'hello'>; // 'olleh'

Here we use an accumulator pattern—each character is prepended to the accumulator as we recurse through the string.

Example: Parsing Path Segments

type Split<S extends string, Delimiter extends string = '/'> = 
  S extends `${infer Segment}${Delimiter}${infer Rest}`
    ? [Segment, ...Split<Rest, Delimiter>]
    : [S];

type Path = Split<'users/123/posts'>; // ['users', '123', 'posts']

This recursively extracts segments between delimiters, building up a tuple of parts.

Key Takeaway: Type-level string manipulation uses template literals with infer in recursive conditional types to parse and transform string literal types, enabling powerful compile-time string processing patterns like parsing paths, reversing strings, or extracting tokens.