Prefix and Suffix Patterns
You'll learn: How to create type-safe string patterns with known prefixes or suffixes using template literal types.
What Are Prefix and Suffix Patterns?
When you know certain strings in your application will always start or end with specific text, you can encode that rule directly in the type system. Template literal types let you define patterns like "user-${string}" (prefix) or "${string}EventHandler" (suffix), ensuring strings conform to your naming conventions.
This is incredibly useful for:
- API routes (
"/api/${string}") - CSS class names (
"btn-${string}") - Event names (
"on${string}"or"${string}Changed") - Database column prefixes (
"user_${string}")
Prefix Patterns
Create types where strings must start with specific text:
type ApiRoute = `/api/${string}`;
const validRoute: ApiRoute = "/api/users"; // ✓ Valid
const alsoValid: ApiRoute = "/api/posts/123"; // ✓ Valid
// const invalid: ApiRoute = "/users"; // ✗ Error
Suffix Patterns
Create types where strings must end with specific text:
type EventHandler = `on${string}`;
const clickHandler: EventHandler = "onClick"; // ✓ Valid
const loadHandler: EventHandler = "onLoad"; // ✓ Valid
// const wrong: EventHandler = "handleClick"; // ✗ Error
Combining with Unions
Prefix and suffix patterns become powerful with union types:
type ButtonVariant = "primary" | "secondary" | "danger";
type ButtonClass = `btn-${ButtonVariant}`;
// Result: "btn-primary" | "btn-secondary" | "btn-danger"
const btnClass: ButtonClass = "btn-primary"; // ✓ Valid
Key Takeaway: Prefix and suffix patterns with template literal types enforce naming conventions at compile time, catching mistakes in route names, CSS classes, event handlers, and other string-based APIs before runtime.