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

infer with Template Literal Types

Using infer within template literal types to extract and capture parts of string literal type patterns.

Using infer with Template Literal Types

What you'll learn: How to extract and capture parts of string literal types by combining TypeScript's infer keyword with template literal type patterns.


The Core Idea

You already know that infer lets you extract types from patterns, and template literal types let you match string shapes. When you combine them, you can parse and extract parts of string literal types at the type level.

Think of it like using a regular expression to capture groups in a string—but instead of runtime string matching, you're doing it entirely in TypeScript's type system.


Basic Pattern Extraction

The general pattern looks like this:

type ExtractName<T> = T extends `hello ${infer Name}` ? Name : never;

type Result1 = ExtractName<"hello world">;  // "world"
type Result2 = ExtractName<"hello TypeScript">;  // "TypeScript"
type Result3 = ExtractName<"goodbye world">;  // never

Here, infer Name captures whatever comes after "hello " in the string literal type.


Extracting from Different Positions

You can extract from the beginning, middle, or end:

// Extract prefix
type GetPrefix<T> = T extends `${infer Prefix}_${string}` ? Prefix : never;
type P = GetPrefix<"user_name">;  // "user"

// Extract suffix
type GetSuffix<T> = T extends `${string}_${infer Suffix}` ? Suffix : never;
type S = GetSuffix<"user_name">;  // "name"

// Extract middle part
type GetMiddle<T> = T extends `${string}_${infer Middle}_${string}` ? Middle : never;
type M = GetMiddle<"start_middle_end">;  // "middle"

Multiple infer Variables

You can capture multiple parts simultaneously:

type ParsePath<T> = T extends `/${infer First}/${infer Second}`
  ? { first: First; second: Second }
  : never;

type Route = ParsePath<"/users/123">;
// { first: "users"; second: "123" }

Practical Use Case: Route Parameter Extraction

type ExtractParams<T> = T extends `${string}:${infer Param}/${infer Rest}`
  ? Param | ExtractParams<`/${Rest}`>
  : T extends `${string}:${infer Param}`
  ? Param
  : never;

type Params = ExtractParams<"/users/:userId/posts/:postId">;
// "userId" | "postId"

This recursively extracts all route parameter names from a path pattern.


Key Takeaway: Combining infer with template literal types lets you perform compile-time string parsing, extracting specific segments from string literal type patterns—perfect for type-safe routing, parsing, and string manipulation at the type level.