Bird
Raised Fist0
Typescriptprogramming~10 mins

Pattern matching with template literals in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Pattern matching with regex
Start with input string
↓
Define regex pattern
↓
Use match or regex to compare
↓
If matches
↓
Extract parts
↓
Use extracted values
This flow shows how a string is checked against a regex pattern, extracting parts if it matches.
Execution Sample
Typescript
const input = 'user:1234';
const pattern = /user:(\d+)/;
const match = input.match(pattern);
if (match) {
  console.log(`ID is ${match[1]}`);
}
This code matches a string against a pattern to extract a number after 'user:' and prints it.
Execution Table
StepActionInputPatternMatch ResultExtracted ValueOutput
1Define input stringuser:1234
2Define regex pattern/user:(\d+)/
3Match input with patternuser:1234/user:(\d+)/Match found1234
4Check if match existsYes1234
5Print extracted ID1234ID is 1234
💡 Matching completes after extracting number and printing output.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
inputundefineduser:1234user:1234user:1234
patternundefinedundefined/user:(\d+)//user:(\d+)/
matchundefinedundefined["user:1234", "1234"]["user:1234", "1234"]
Key Moments - 2 Insights
Why does match[1] contain '1234' instead of the whole string?
match[0] is the full matched string 'user:1234', while match[1] is the first captured group (\d+), which is '1234' as shown in execution_table step 3.
What happens if the input does not match the pattern?
The match variable becomes null, so the if condition fails and no extraction or output happens, as implied by the 'No' branch in concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'match' after step 3?
A["user:1234", "1234"]
Bnull
C"user:1234"
D"1234"
💡 Hint
Check the 'Match Result' and 'Extracted Value' columns in step 3 of execution_table.
At which step does the program print the output?
AStep 3
BStep 4
CStep 5
DStep 2
💡 Hint
Look at the 'Output' column in execution_table to find when output occurs.
If the input was 'admin:5678', what would happen to the 'match' variable?
AIt would match and extract '5678'
BIt would be null because pattern expects 'user:' prefix
CIt would throw an error
DIt would match the whole string
💡 Hint
Refer to the pattern in execution_sample and how match works in execution_table step 3.
Concept Snapshot
Pattern matching with regex uses regex to check if a string fits a pattern.
Use capturing groups (parentheses) to extract parts.
match() returns an array if matched, null if not.
match[0] is full match, match[1..] are captured groups.
Use if-check to safely extract and use values.
Full Transcript
This visual trace shows how regex pattern matching works in TypeScript. We start with an input string 'user:1234' and a regex pattern /user:(\d+)/. The program uses input.match(pattern) to check if the input fits the pattern. If it matches, match is an array where match[0] is the full string and match[1] is the captured number '1234'. The program then prints 'ID is 1234'. If the input does not match, match is null and no output occurs. Variables like input, pattern, and match change as the program runs, shown step-by-step. Common confusions include why match[1] holds the number and what happens if no match is found. The quiz tests understanding of match values and program flow. This helps beginners see exactly how pattern matching extracts data from strings.

Practice

(1/5)
1. What does pattern matching with template literals in TypeScript primarily help you do?
easy
A. Create new variables dynamically
B. Automatically generate functions from strings
C. Change the type of a variable at runtime
D. Check if a string fits a specific shape or format

Solution

  1. Step 1: Understand the purpose of pattern matching

    Pattern matching with template literals is used to verify if strings follow a certain pattern or format.
  2. Step 2: Relate to template literals usage

    Template literals allow embedding expressions and patterns to check string shapes easily.
  3. Final Answer:

    Check if a string fits a specific shape or format -> Option D
  4. Quick Check:

    Pattern matching = Check string shape [OK]
Hint: Pattern matching checks string shapes, not variable types [OK]
Common Mistakes:
  • Confusing pattern matching with variable creation
  • Thinking it changes variable types
  • Assuming it generates functions automatically
2. Which of the following is the correct syntax to use a template literal pattern in a TypeScript type check?
easy
A. type ID = `${string}-${number}`;
B. type ID = '${string}-${number}';
C. ;`}rebmun{$-}gnirts{$` = DI epyt
D. type ID = `${string}-${number}`

Solution

  1. Step 1: Identify correct template literal syntax

    Template literals use backticks (`) and embed types inside ${} without quotes.
  2. Step 2: Check for correct punctuation

    type ID = `${string}-${number}`; correctly uses backticks and ${} with no extra quotes.
  3. Final Answer:

    type ID = `${string}-${number}`; -> Option A
  4. Quick Check:

    Backticks + ${} = correct syntax [OK]
Hint: Use backticks and ${} without quotes for template types [OK]
Common Mistakes:
  • Using single or double quotes instead of backticks
  • Putting quotes inside ${} expressions
  • Missing backticks around the pattern
3. What will be the result of this TypeScript code snippet?
type Email = `${string}@${string}.com`;

function isEmail(value: string): value is Email {
  return /.+@.+\.com$/.test(value);
}

console.log(isEmail('user@example.com'));
console.log(isEmail('user@example.org'));
medium
A. true\ntrue
B. false\ntrue
C. true\nfalse
D. false\nfalse

Solution

  1. Step 1: Understand the Email type pattern

    The Email type expects strings like 'something@something.com'.
  2. Step 2: Analyze the isEmail function

    The regex checks if the string ends with '.com' after an '@' symbol.
  3. Step 3: Check the console.log outputs

    'user@example.com' matches the regex, so true; 'user@example.org' does not, so false.
  4. Final Answer:

    true false -> Option C
  5. Quick Check:

    Regex matches .com only = true, false [OK]
Hint: Regex matches only .com emails, others return false [OK]
Common Mistakes:
  • Assuming .org matches .com pattern
  • Ignoring regex anchors
  • Confusing true/false order in output
4. Identify the error in this TypeScript code using template literal pattern matching:
type Phone = `${number}-${number}-${number}`;

function isPhone(value: string): value is Phone {
  return /^\d{3}-\d{3}-\d{4}$/.test(value);
}
medium
A. The Phone type pattern does not match the regex format
B. The regex pattern is missing anchors
C. Template literals cannot use number types inside ${}
D. The function should return a boolean, not a type predicate

Solution

  1. Step 1: Compare Phone type and regex pattern

    Phone type expects three numbers separated by dashes, but each ${number} matches any number, not fixed digits.
  2. Step 2: Check regex pattern details

    The regex expects exactly 3 digits, then 3 digits, then 4 digits, which doesn't align with the Phone type's generic number placeholders.
  3. Final Answer:

    The Phone type pattern does not match the regex format -> Option A
  4. Quick Check:

    Type pattern and regex must align [OK]
Hint: Match template literal types exactly with regex patterns [OK]
Common Mistakes:
  • Assuming ${number} matches fixed digit counts
  • Ignoring regex anchors (though present here)
  • Confusing return type of type predicate functions
5. Given this TypeScript code, what will be the output?
type UserID = `user_${number}`;

function parseUserID(id: string): UserID | null {
  if (id.match(/^user_\d+$/)) {
    return id as UserID;
  }
  return null;
}

console.log(parseUserID('user_123'));
console.log(parseUserID('admin_123'));
hard
A. null\nnull
B. 'user_123'\nnull
C. 'user_123'\n'user_123'
D. null\n'user_123'

Solution

  1. Step 1: Understand UserID type pattern

    UserID must start with 'user_' followed by a number.
  2. Step 2: Analyze parseUserID function

    The function returns the id cast as UserID if it matches the regex /^user_\d+$/, else returns null.
  3. Step 3: Evaluate console.log outputs

    'user_123' matches regex, so returns 'user_123'; 'admin_123' does not, so returns null.
  4. Final Answer:

    'user_123' null -> Option B
  5. Quick Check:

    Regex match returns id, else null [OK]
Hint: Regex match controls return; unmatched returns null [OK]
Common Mistakes:
  • Assuming 'admin_123' matches user pattern
  • Confusing return types with casting
  • Ignoring regex anchors and pattern
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard