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

Extracting String Literal Prefixes and Suffixes

Use template literal types with infer to extract parts of string literal types.

Extracting String Literal Prefixes and Suffixes

What you'll learn: How to use template literal types with infer to extract parts of string literal types based on patterns.

The Core Idea

Just as you can use infer to extract parts of functions or arrays, you can use it with template literal types to parse string literal types and extract specific segments. Think of it like pattern matching for strings — you provide a template pattern, and TypeScript extracts the matching pieces into type variables.

This is similar to using regular expressions to capture groups in JavaScript, except it happens entirely at the type level and works with literal string types.

Basic Prefix Extraction

You can extract a prefix by placing infer after a known literal pattern:

type RemovePrefix<S extends string> = S extends `prefix_${infer Rest}`
  ? Rest
  : S;

type Result1 = RemovePrefix<"prefix_hello">; // "hello"
type Result2 = RemovePrefix<"prefix_world">; // "world"
type Result3 = RemovePrefix<"nope">;         // "nope" (no match)

Basic Suffix Extraction

You can extract a suffix by placing infer before a known literal pattern:

type RemoveSuffix<S extends string> = S extends `${infer Start}_suffix`
  ? Start
  : S;

type Result4 = RemoveSuffix<"hello_suffix">; // "hello"
type Result5 = RemoveSuffix<"world_suffix">; // "world"
type Result6 = RemoveSuffix<"nope">;         // "nope" (no match)

Extracting the Middle

You can use multiple infer keywords to extract different parts:

type ExtractMiddle<S extends string> = S extends `${string}_${infer Middle}_${string}`
  ? Middle
  : never;

type Result7 = ExtractMiddle<"prefix_DATA_suffix">; // "DATA"
type Result8 = ExtractMiddle<"a_b_c">;              // "b"

Practical Example: Route Parameter Extraction

type ExtractParam<S extends string> = S extends `${string}:${infer Param}/${string}`
  ? Param
  : S extends `${string}:${infer Param}`
  ? Param
  : never;

type Param1 = ExtractParam<"/users/:id">;        // "id"
type Param2 = ExtractParam<"/posts/:slug/edit">; // "slug"

Real-World Pattern: Event Name Parsing

type ExtractEventType<S extends string> = S extends `on${infer EventName}`
  ? EventName
  : never;

type Event1 = ExtractEventType<"onClick">;     // "Click"
type Event2 = ExtractEventType<"onHover">;     // "Hover"
type Event3 = ExtractEventType<"someMethod">;  // never

Key Takeaway: Template literal types combined with infer let you pattern-match and extract segments from string literal types, enabling powerful string parsing at the type level — perfect for type-safe APIs that work with structured string patterns like routes, event names, or configuration keys.