0
0
Typescriptprogramming~20 mins

Building type-safe string patterns in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type-Safe String Pattern Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a template literal type with union
What is the type of Greeting and what will message contain after assignment?
Typescript
type Name = "Alice" | "Bob";
type Greeting = `Hello, ${Name}!`;

const message: Greeting = "Hello, Alice!";

console.log(message);
A"Hello, Charlie!"
B"Hello, Alice!"
CType error at assignment
D"Hello, Bob!"
Attempts:
2 left
💡 Hint
Check which strings are allowed by the template literal type.
🧠 Conceptual
intermediate
2:00remaining
Understanding type-safe string pattern constraints
Which of the following TypeScript types correctly restricts a string to only the patterns 'user-123' or 'admin-456'?
Atype ID = 'user-123' | 'admin-456';
Btype ID = string & (`user-123` | `admin-456`);
Ctype ID = `user-${number}` | `admin-${number}`;
Dtype ID = `${string}-${number}`;
Attempts:
2 left
💡 Hint
Think about exact string matches versus patterns.
🔧 Debug
advanced
2:00remaining
Identify the error in this type-safe string pattern
What error does this TypeScript code produce?
Typescript
type Event = `on${Capitalize<string>}`;

const clickEvent: Event = "onclick";
ASyntax error: Invalid template literal type
BRuntime error: Cannot capitalize string
CNo error, code compiles fine
DType error: 'onclick' is not assignable to type 'Event'
Attempts:
2 left
💡 Hint
Check what Capitalize means in a template literal type.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a type-safe pattern for hex colors?
Choose the option that correctly defines a TypeScript type for strings matching a hex color code like '#A1B2C3'.
Atype HexColor = `#${string}`;
Btype HexColor = `#${string & { length: 6 }}`;
Ctype HexColor = `#${Uppercase<string>}${Uppercase<string>}${Uppercase<string>}${Uppercase<string>}${Uppercase<string>}${Uppercase<string>}`;
Dtype HexColor = `#${string & { length: 6, pattern: /^[0-9A-F]{6}$/ }}`;
Attempts:
2 left
💡 Hint
TypeScript template literal types cannot enforce length or regex patterns directly.
🚀 Application
expert
2:00remaining
Determine the number of valid strings for this type-safe pattern
Given the type type Code = `${'A' | 'B'}${1 | 2 | 3}`;, how many unique strings are assignable to Code?
A5
B3
C6
D9
Attempts:
2 left
💡 Hint
Multiply the number of options in each union to find total combinations.