0
0
Typescriptprogramming~5 mins

Pattern matching with template literals in Typescript

Choose your learning style9 modes available
Introduction

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.

You want to check if a string starts with a specific word followed by some numbers.
You need to extract parts of a string that follow a known format.
You want to compare strings that have a fixed pattern but variable parts.
You want to write cleaner code instead of using complex regular expressions.
You want to handle strings with placeholders or templates in a readable way.
Syntax
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.

Examples
Check if string starts with 'hello' using template literal.
Typescript
const greeting = 'hello123';
if (greeting.startsWith(`hello`)) {
  console.log('Pattern matched!');
}
Match string starting with 'user' followed by digits using regex (template literals help build patterns).
Typescript
const input = 'user42';
if (input.match(/^user\d+$/)) {
  console.log('User pattern matched');
}
Use TypeScript template literal types to enforce string pattern at compile time.
Typescript
type ID = `item-${number}`;
const id: ID = 'item-123';
console.log(id);
Edge case: empty string does not match pattern.
Typescript
const empty = '';
if (empty.startsWith(`hello`)) {
  console.log('Won\'t print');
} else {
  console.log('No match for empty string');
}
Sample Program

This program checks if strings match the pattern 'user' followed by numbers using a regular expression. Template literals help build readable messages.

Typescript
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');
OutputSuccess
Important Notes

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.

Summary

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.