

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Unions
incomplete
2: Optional Parameters
incomplete
3: Default Parameters
incomplete
4: Literal Types
incomplete
5: Value Unions
incomplete
6: Template Literal Types
incomplete
7: Giant Unions
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
This is one of the more unhinged features of TypeScript (at least in my opinion), but it is really cool and insanely powerful when you find a good use case for it.
Remember literal types and type unions?
type Class = "wizard" | "warrior" | "rogue";
Well, you can also create literal types using string templates:
type Hero = `elf ${Class}`;
The type of Class expands automatically to the possible values, so the above is the same as:
type Hero = "elf wizard" | "elf warrior" | "elf rogue";
You can also get crazy and combine all the combinations of two types:
type Class = "wizard" | "warrior" | "rogue";
type Race = "elf" | "human" | "dwarf";
type Hero = `Hero: ${Race} ${Class}`;
// Hero: elf wizard | Hero: elf warrior | Hero: elf rogue | Hero: human wizard | Hero: human warrior | Hero: human rogue | Hero: dwarf wizard | Hero: dwarf warrior | Hero: dwarf rogue
You can also create types that enforce a simple pattern match. For example:
type LogRecord = `${string}: ${number}`;
// this is valid because it's a string followed by a colon and a number
const criticalErr: LogRecord = "CRITICAL: 69";
// these are all invalid
const criticalErr: LogRecord = "CRITICAL 92";
const criticalErr: LogRecord = "CRITICAL: 92a";
const criticalErr: LogRecord = "92: CRITICAL";
Support.ai needs a standardized logging system where each log message must have a specific format to ensure consistent parsing and indexing.
info: User logged inerror: Database connection failed.api_123database_456