We want to create strings that follow specific rules and catch mistakes early. Type-safe string patterns help us check these rules while writing code, so errors don't happen later.
0
0
Building type-safe string patterns in Typescript
Introduction
When you want to make sure a string matches a format like an email or phone number.
When you build URLs or file paths that must follow a certain pattern.
When you want to restrict user input to specific string shapes.
When you want to avoid bugs caused by wrong string formats in your program.
Syntax
Typescript
type Pattern = `${string}-${number}`; // Example: a string with text, a dash, then a number
Use template literal types with backticks `` to build string patterns.
You can combine string, number, and literal values inside the pattern.
Examples
This pattern requires the string to start with "user-" and end with a number.
Typescript
type UserId = `user-${number}`; const id1: UserId = "user-123"; // valid const id2: UserId = "user-abc"; // error
This pattern ensures the string ends with ".txt".
Typescript
type FileName = `${string}.txt`; const file1: FileName = "notes.txt"; // valid const file2: FileName = "image.png"; // error
This pattern requires the string to start with a hash (#).
Typescript
type ColorCode = `#${string}`; const color1: ColorCode = "#ff0000"; // valid const color2: ColorCode = "ff0000"; // error
Sample Program
This program defines a type-safe string pattern for order IDs. It only accepts strings like "order-123". Trying to use a wrong format causes a TypeScript error before running the program.
Typescript
type OrderId = `order-${number}`; function printOrder(id: OrderId) { console.log(`Order ID is: ${id}`); } printOrder("order-456"); // printOrder("order-abc"); // This line would cause a TypeScript error
OutputSuccess
Important Notes
TypeScript checks these patterns only at compile time, not at runtime.
Use these patterns to catch mistakes early and improve code safety.
Summary
Type-safe string patterns help you define exact string formats in your code.
They use template literal types with placeholders like ${string} and ${number}.
This technique prevents bugs by checking string shapes while coding.