Course contentsShow
← TypeScript
Lesson 798 of 1,79618. Conditional TypesFree lesson

infer in Template Literal Types

Combining infer with template literal types to extract substrings and parse type-level string patterns.

infer in Template Literal Types

What you'll learn: How to combine infer with template literal types to extract substrings and parse structured strings at the type level.

The Concept

You've already learned that infer lets you extract parts of a type within conditional expressions, and you know template literal types work with string patterns. When you combine them, you unlock the ability to parse and extract portions of string literal types based on patterns—essentially regex-like operations at the type level.

Think of it like pattern matching for strings, but happening entirely in TypeScript's type system. You can "cut up" strings like "firstName" into "first" and "Name", or extract IDs from paths like "/user/123".

How It Works

Use template literals in the extends clause with infer placeholders to capture substrings:

// Extract everything before "Event"
type ExtractName<T> = T extends `${infer Name}Event` 
  ? Name 
  : never;

type A = ExtractName<"clickEvent">;     // "click"
type B = ExtractName<"hoverEvent">;     // "hover"
type C = ExtractName<"submit">;         // never

You can capture multiple parts:

// Parse a path pattern
type ParsePath<T> = T extends `/user/${infer ID}/post/${infer PostID}`
  ? { userId: ID; postId: PostID }
  : never;

type Route = ParsePath<"/user/42/post/99">;  
// { userId: "42"; postId: "99" }

Extract prefixes or suffixes:

type RemovePrefix<T> = T extends `get${infer Rest}` ? Rest : T;

type X = RemovePrefix<"getName">;  // "Name"
type Y = RemovePrefix<"name">;     // "name"

Common Use Cases

String parsing is powerful for API routes, event names, CSS classes, or any structured naming convention where you want type-safe extraction of components.

Key Takeaway: Combining infer with template literal types enables pattern matching and substring extraction at the type level, letting you parse and transform structured string types with precision.