Discover string template literal types to construct complex pattern-based string types dynamically at compile time.
Discover how TypeScript infers types automatically and how let versus const declarations shape wide types versus narrow literal types.
TypeScript allows you to manipulate literal types using string template literal syntax directly in the type system.
Just as template literals construct strings at runtime, Template Literal Types construct string types at compile time:
type EventType = "click" | "hover" | "focus";
type Component = "button" | "input" | "card";
// Automatically generates 9 literal string combinations!
type DOMEventName = `${Component}:${EventType}`;
// Inferred as: "button:click" | "button:hover" | "input:click" | ...
const handleEvent = (event: DOMEventName) => {
console.log("Handling:", event);
};
handleEvent("button:click"); // Valid!
// handleEvent("header:click"); // Error: Type "header:click" is not assignable
Use template literal types to enforce API route paths or CSS spacing tokens:
type HTTPMethod = "GET" | "POST";
type APIVersion = "v1" | "v2";
type Endpoint = `/api/${APIVersion}/${string}`;
const validRoute: Endpoint = "/api/v1/users";
// const badRoute: Endpoint = "/v1/users"; // Error: Must start with /api/
TypeScript provides built-in intrinsic string manipulation type utilities:
Uppercase<StringType>Lowercase<StringType>Capitalize<StringType>Uncapitalize<StringType>type Action = "create" | "update";
type GetterName = `get${Capitalize<Action>}`; // "getCreate" | "getUpdate"
Use template literal types for design system tokens and API route validation. Next, let's explore Type Assertions and as unknown as T!