0
0
Typescriptprogramming~5 mins

Pattern matching with template literals in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
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?<br>
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
What will ExtractName<'Hello, Bob!'> return if type ExtractName<T> = T extends `Hello, ${infer Name}!` ? Name : never;?
Anever
B'Bob'
C'Hello, Bob!'
Dstring
If a string does not match the pattern in a conditional template literal type, what is the result?
Anever
Bstring
Cundefined
Dany
Can template literal pattern matching be used to validate string formats at compile time?
AOnly at runtime
BNo
CYes
DOnly with regular expressions
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`
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.