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

HTTP Method Types from Routes

Transform route definitions into method-specific types using mapped types with template literal combinations.

HTTP Method Types from Routes

What you'll learn: How to automatically generate HTTP method-specific types (GET, POST, etc.) from route definitions using mapped types and template literal combinations.


When building type-safe APIs, you often define routes like /users/:id or /posts and want TypeScript to understand which HTTP methods apply to which routes. You can transform a route definition object into separate types for each method using mapped types with template literals.

The Core Pattern

Imagine you have an API route configuration that specifies which methods are allowed on which endpoints:

type APIRoutes = {
  '/users': 'GET' | 'POST';
  '/users/:id': 'GET' | 'PUT' | 'DELETE';
  '/posts': 'GET' | 'POST';
};

You can create method-specific types by combining mapped types with template literals:

type GetRoutes<T> = {
  [K in keyof T]: 'GET' extends T[K] ? K : never;
}[keyof T];

type GetEndpoints = GetRoutes<APIRoutes>;
// Result: '/users' | '/users/:id' | '/posts'

Building Multiple Method Types

For all HTTP methods, you'd create a pattern that generates each set:

type RoutesForMethod<T, Method extends string> = {
  [K in keyof T]: Method extends T[K] ? K : never;
}[keyof T];

type GET_Routes = RoutesForMethod<APIRoutes, 'GET'>;
// '/users' | '/users/:id' | '/posts'

type POST_Routes = RoutesForMethod<APIRoutes, 'POST'>;
// '/users' | '/posts'

type DELETE_Routes = RoutesForMethod<APIRoutes, 'DELETE'>;
// '/users/:id'

This pattern filters routes by checking if a method exists in the union of allowed methods for each route, returning never for non-matching routes. The [keyof T] lookup extracts only the non-never values.

Key Takeaway: Mapped types with template literal combinations let you slice route definitions into method-specific unions, creating type-safe API contracts that prevent calling unavailable methods on specific endpoints.