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

Validating HTTP Method and Path Combinations

Combine template literals with mapped types to enforce which HTTP methods are valid for specific route patterns.

Validating HTTP Method and Path Combinations

What you'll learn: How to use template literal types with mapped types to enforce that only specific HTTP methods are valid for particular route patterns at compile time.


Why This Matters

In REST APIs, not all HTTP methods make sense for every endpoint. For example, you might want GET /users/:id to be valid but prevent DELETE /users (requiring an ID for deletion). Template literal types let you encode these rules directly in your type system, catching invalid method-path combinations before runtime.

The Core Pattern

You can combine template literals with mapped types to create a type that only allows specific method-path pairs:

type UserRoutes = {
  'GET /users': void;
  'GET /users/:id': void;
  'POST /users': void;
  'DELETE /users/:id': void;
};

But hardcoding every combination isn't scalable. Instead, use template literals with conditional logic:

type HttpMethod = 'GET' | 'POST' | 'DELETE';
type UserPath = '/users' | '/users/:id';

// Only allow DELETE with :id routes
type ValidRoutes<M extends HttpMethod, P extends UserPath> =
  M extends 'DELETE'
    ? P extends `${string}:id`
      ? `${M} ${P}`
      : never
    : `${M} ${P}`;

type AllowedRequests = ValidRoutes<HttpMethod, UserPath>;
// Result: "GET /users" | "GET /users/:id" | "POST /users" | "POST /users/:id" | "DELETE /users/:id"

This pattern ensures DELETE /users is excluded because deletion requires an ID parameter.

Practical Application

Map over methods and paths together:

type CreateRoutes<Methods extends string, Paths extends string> = {
  [M in Methods]: {
    [P in Paths]: `${M} ${P}`;
  }[Paths];
}[Methods];

Key Takeaway: Template literal types combined with mapped types and conditional logic let you enforce valid HTTP method-path combinations at compile time, preventing impossible or dangerous API calls before they reach production.