Pattern matching with template literals helps you check if a string fits a certain shape or pattern easily. It makes working with strings clearer and simpler.
Pattern matching with template literals in Typescript
function matchPattern(input: string) { const prefix = 'prefix'; if (input.match(new RegExp(`^${prefix}\d+$`))) { // code when pattern matches } } // Or using template literal types for compile-time checks type Greeting = `hello${string}`; const greeting: Greeting = 'hello123'; if (greeting.startsWith('hello')) { // matched (runtime check) }
Template literals use backticks (`) and can embed expressions with ${}.
TypeScript 4.1+ supports template literal types for compile-time string pattern checks.
const greeting = 'hello123'; if (greeting.startsWith(`hello`)) { console.log('Pattern matched!'); }
const input = 'user42'; if (input.match(/^user\d+$/)) { console.log('User pattern matched'); }
type ID = `item-${number}`; const id: ID = 'item-123'; console.log(id);
const empty = ''; if (empty.startsWith(`hello`)) { console.log('Won\'t print'); } else { console.log('No match for empty string'); }
This program checks if strings match the pattern 'user' followed by numbers using a regular expression. Template literals help build readable messages.
function checkUserID(userID: string) { // Check if userID matches pattern 'user' followed by digits if (/^user\d+$/.test(userID)) { console.log(`User ID '${userID}' matches the pattern.`); } else { console.log(`User ID '${userID}' does NOT match the pattern.`); } } console.log('Before checking IDs:'); checkUserID('user123'); checkUserID('admin456'); checkUserID('user'); checkUserID('user007');
Time complexity of pattern matching with regex is generally O(n), where n is string length.
Space complexity is O(1) for simple matches, but can grow with complex patterns.
Common mistake: confusing template literals with regular expressions; template literals create strings, regex tests patterns.
Use pattern matching with template literals for simple, readable checks; use regex for complex patterns.
Pattern matching with template literals helps check string shapes simply.
Use template literals to build readable string patterns and messages.
Combine with regex for powerful pattern checks in TypeScript.