S SmartDocs
系列: Typescript typescript 73 行 · 更新於 2025-12-27

04-template-literal-types.ts

Typescript/src/03-advanced/04-template-literal-types.ts

// ============================================
// 04. Template Literal Types
// ============================================

// Basic Template Literals
type Greeting = `Hello, ${string}`;
// "Hello, " + any string

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">;
// "onClick"

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type ApiEndpoint = `/${string}`;
type ApiRoute = `${HttpMethod} ${ApiEndpoint}`;

type Route = "GET /users" | "POST /users" | "GET /posts";

// String Manipulation Types
type T0 = Uppercase<"hello">;      // "HELLO"
type T1 = Lowercase<"WORLD">;      // "world"
type T2 = Capitalize<"hello">;      // "Hello"
type T3 = Uncapitalize<"Hello">;   // "hello"

// Pattern Matching
type ExtractRoute<T extends string> = T extends `${infer Method} ${infer Path}`
  ? { method: Method; path: Path }
  : never;

type RouteExample = ExtractRoute<"GET /users">;
// { method: "GET"; path: "/users" }

// Extract Parts
type ExtractMethod<T extends string> = T extends `${infer M} ${string}`
  ? M
  : never;

type ExtractPath<T extends string> = T extends `${string} ${infer P}`
  ? P
  : never;

type Method = ExtractMethod<"GET /users">; // "GET"
type Path = ExtractPath<"GET /users">;     // "/users"

// CSS Class Names
type Color = "red" | "blue" | "green";
type Size = "small" | "medium" | "large";
type ButtonClass = `btn-${Color}-${Size}`;

// API Route Types
type HttpMethod2 = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
type Resource = "users" | "posts" | "comments";
type IdParam = `${Resource}/${string}`;
type ApiRoute2 = `${HttpMethod2} /api/${IdParam}`;

// Path Parsing
type Split<S extends string, D extends string> = S extends `${infer Head}${D}${infer Tail}`
  ? [Head, ...Split<Tail, D>]
  : [S];

type PathParts = Split<"a/b/c", "/">;
// ["a", "b", "c"]

// Example usage function
function handleRoute(route: Route): void {
  console.log(`Handling route: ${route}`);
}

// handleRoute("GET /users"); // OK
// handleRoute("INVALID"); // Error

export { handleRoute };

相關文章