We want to create strings that follow specific rules and catch mistakes early. Type-safe string patterns help us check these rules while writing code, so errors don't happen later.
Building type-safe string patterns in Typescript
type Pattern = `${string}-${number}`; // Example: a string with text, a dash, then a number
Use template literal types with backticks `` to build string patterns.
You can combine string, number, and literal values inside the pattern.
type UserId = `user-${number}`; const id1: UserId = "user-123"; // valid const id2: UserId = "user-abc"; // error
type FileName = `${string}.txt`; const file1: FileName = "notes.txt"; // valid const file2: FileName = "image.png"; // error
type ColorCode = `#${string}`; const color1: ColorCode = "#ff0000"; // valid const color2: ColorCode = "ff0000"; // error
This program defines a type-safe string pattern for order IDs. It only accepts strings like "order-123". Trying to use a wrong format causes a TypeScript error before running the program.
type OrderId = `order-${number}`; function printOrder(id: OrderId) { console.log(`Order ID is: ${id}`); } printOrder("order-456"); // printOrder("order-abc"); // This line would cause a TypeScript error
TypeScript checks these patterns only at compile time, not at runtime.
Use these patterns to catch mistakes early and improve code safety.
Type-safe string patterns help you define exact string formats in your code.
They use template literal types with placeholders like ${string} and ${number}.
This technique prevents bugs by checking string shapes while coding.
Practice
Solution
Step 1: Understand type-safe string patterns
Type-safe string patterns use TypeScript's template literal types to enforce string formats during coding.Step 2: Identify the benefit
This enforcement helps catch errors early by ensuring strings match expected patterns before running the program.Final Answer:
They ensure strings follow a specific format at compile time. -> Option AQuick Check:
Type-safe string patterns = compile-time format check [OK]
- Thinking they improve runtime speed
- Confusing with string-to-number conversion
- Assuming they change string behavior at runtime
Solution
Step 1: Recognize template literal type syntax
Type-safe string patterns use backticks and ${} placeholders, like `https://${string}`.Step 2: Compare options
type URL = `https://${string}`; uses correct template literal syntax. Options A, B, and D use invalid or incorrect TypeScript syntax for this purpose.Final Answer:
type URL = `https://${string}`; -> Option DQuick Check:
Template literal type syntax = backticks + ${} [OK]
- Using quotes with + for concatenation in types
- Using & or | operators incorrectly
- Not using backticks for template literals
type ID = `user_${number}`;, which of the following assignments will cause a TypeScript error?Solution
Step 1: Understand the pattern
The type ID requires strings starting with 'user_' followed by a number.Step 2: Check each assignment
A is 'user_123' (valid number), B is 'user_0' (valid number), C uses template literal with number 456 (valid), D is 'user_abc' (letters, invalid).Final Answer:
const b: ID = 'user_abc'; causes error -> Option CQuick Check:
Pattern requires number after 'user_' = D error [OK]
- Assuming any string after prefix is valid
- Confusing template literal with runtime string
- Ignoring number type constraint
type Email = `${string}@${string}.com`;
const myEmail: Email = 'john.doe@gmail';Solution
Step 1: Analyze the type Email pattern
Email requires a string, then '@', then another string, then '.com' exactly.Step 2: Check the assigned value
myEmail is 'john.doe@gmail' missing the '.com' suffix, so it does not match the pattern.Final Answer:
The type Email does not allow missing '.com' suffix. -> Option BQuick Check:
Pattern requires '.com' suffix = missing causes error [OK]
- Ignoring required suffix in pattern
- Thinking '@' is invalid in template literals
- Confusing type errors with runtime errors
v1.2.3 where each number can be one or more digits. Which of these TypeScript types correctly enforces this pattern?Solution
Step 1: Understand the version pattern
The version string starts with 'v' followed by three numbers separated by dots.Step 2: Evaluate each type
A uses number for all three parts, matching the pattern exactly. B uses string, allowing invalid formats. C mixes number and string incorrectly. D misses the third number part.Final Answer:
type Version = `v${number}.${number}.${number}`; -> Option AQuick Check:
All parts as number with dots = type Version = `v${number}.${number}.${number}`; [OK]
- Using string instead of number for numeric parts
- Missing parts of the pattern
- Mixing types inconsistently
Ready to prove it?
Pass the test and this pattern moves unknown
