What is pattern matching with template literals in TypeScript?
It is a way to check if a string fits a specific pattern using template literal types, allowing you to extract parts of the string or validate its format at compile time.
Click to reveal answer
intermediate
How do you extract parts of a string using template literal pattern matching?
You use the infer keyword inside a conditional type with template literals to capture parts of the string into type variables.
Click to reveal answer
intermediate
Example: What does this type do?
type ExtractName<T> = T extends `Hello, ${infer Name}!` ? Name : never;
It extracts the Name part from strings that start with 'Hello, ' and end with '!'. For example, ExtractName<'Hello, Alice!'> = 'Alice'.
Click to reveal answer
advanced
Can template literal pattern matching check for exact string formats at compile time?
Yes, TypeScript can use template literal types in conditional types to verify if a string matches a pattern and produce different types based on that.
Click to reveal answer
beginner
What happens if a string does not match the pattern in a template literal conditional type?
The conditional type returns the 'false' branch, often never or another fallback type, indicating no match.
Click to reveal answer
Which keyword is used to capture parts of a string in template literal pattern matching?
Amatch
Bextract
Ccapture
Dinfer
✗ Incorrect
The infer keyword is used inside conditional types to capture parts of a string matched by template literals.
What will ExtractName<'Hello, Bob!'> return if type ExtractName<T> = T extends `Hello, ${infer Name}!` ? Name : never;?
Anever
B'Bob'
C'Hello, Bob!'
Dstring
✗ Incorrect
The type extracts 'Bob' from the string because it matches the pattern.
If a string does not match the pattern in a conditional template literal type, what is the result?
Anever
Bstring
Cundefined
Dany
✗ Incorrect
The conditional type returns the false branch, often never, indicating no match.
Can template literal pattern matching be used to validate string formats at compile time?
AOnly at runtime
BNo
CYes
DOnly with regular expressions
✗ Incorrect
TypeScript can check string formats at compile time using template literal types and conditional types.
Which of these is a valid pattern for matching a string starting with 'ID-' followed by any characters?
A`ID-${string}`
B`${string}ID-`
C`ID-${number}`
D`${number}-ID`
✗ Incorrect
The pattern `ID-${string}` matches strings starting with 'ID-' followed by any string.
Explain how template literal pattern matching works in TypeScript and how you can extract parts of a string.
Think about how you can capture parts of a string inside a type.
You got /4 concepts.
Describe a use case where pattern matching with template literals can help in TypeScript programming.
Consider how you might check or extract parts of strings without running code.
You got /4 concepts.
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
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.
Step 2: Relate to template literals usage
Template literals allow embedding expressions and patterns to check string shapes easily.
Final Answer:
Check if a string fits a specific shape or format -> Option D
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
Step 1: Identify correct template literal syntax
Template literals use backticks (`) and embed types inside ${} without quotes.
Step 2: Check for correct punctuation
type ID = `${string}-${number}`; correctly uses backticks and ${} with no extra quotes.
Final Answer:
type ID = `${string}-${number}`; -> Option A
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
Step 1: Understand the Email type pattern
The Email type expects strings like 'something@something.com'.
Step 2: Analyze the isEmail function
The regex checks if the string ends with '.com' after an '@' symbol.
Step 3: Check the console.log outputs
'user@example.com' matches the regex, so true; 'user@example.org' does not, so false.
Final Answer:
true
false -> Option C
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
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.
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.
Final Answer:
The Phone type pattern does not match the regex format -> Option A
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
Step 1: Understand UserID type pattern
UserID must start with 'user_' followed by a number.
Step 2: Analyze parseUserID function
The function returns the id cast as UserID if it matches the regex /^user_\d+$/, else returns null.
Step 3: Evaluate console.log outputs
'user_123' matches regex, so returns 'user_123'; 'admin_123' does not, so returns null.
Final Answer:
'user_123'
null -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.