Course contentsShow
← TypeScript
Lesson 823 of 1,79619. Template Literal TypesFree lesson

Multi-Part Template Patterns

Embedding multiple type placeholders in a single template to create complex string patterns like file paths or URLs.

Multi-Part Template Patterns

What you'll learn: How to embed multiple type placeholders in a single template literal type to create complex, validated string patterns like file paths, URLs, and structured identifiers.


The Core Idea

Template literal types aren't limited to single placeholders. You can combine multiple type parameters within one template string to create sophisticated patterns that validate complex string formats at compile time.

Think of it like a form with multiple fields — instead of validating just a first name, you're validating a full address with street, city, and postal code, all in one go.

Multiple Placeholders in Action

type Path<Dir extends string, File extends string, Ext extends string> = 
  `${Dir}/${File}.${Ext}`;

// Valid paths
type ImagePath = Path<"assets/images", "logo", "png">;
// Result: "assets/images/logo.png"

type StylePath = Path<"styles/components", "button", "css">;
// Result: "styles/components/button.css"

Each placeholder (Dir, File, Ext) can be constrained independently, and they combine to form a validated whole.

Union Combinations

When you use unions with multiple placeholders, TypeScript generates all combinations:

type HttpMethod = "GET" | "POST";
type Resource = "users" | "posts";

type Endpoint<Method extends HttpMethod, Resource extends string> = 
  `${Method} /api/${Resource}`;

type API = Endpoint<HttpMethod, Resource>;
// Result: "GET /api/users" | "GET /api/posts" | 
//         "POST /api/users" | "POST /api/posts"

Practical URL Pattern

type Protocol = "http" | "https";
type Domain = string;
type Port = number;

type URL<P extends Protocol, D extends Domain, Port extends number> = 
  `${P}://${D}:${Port}`;

type DevServer = URL<"http", "localhost", 3000>;
// Result: "http://localhost:3000"

Key Takeaway: Multi-part template patterns let you compose complex, type-safe string formats by combining multiple generic placeholders, with each part validated independently while the whole remains cohesive.