A template literal type lets you create new string types by combining unions of string literals with template strings, similar to how template literals work in JavaScript but at the type level.
Click to reveal answer
intermediate
How do unions work with template literal types?
Unions allow multiple string literal types to be combined. When used inside a template literal type, TypeScript creates all possible combinations of those union members as new string literal types.
Click to reveal answer
beginner
Example: What is the resulting type of `type Greeting = `${'Hello' | 'Hi'}, ${'Alice' | 'Bob'}``?
The type Greeting is a union of these string literals: 'Hello, Alice', 'Hello, Bob', 'Hi, Alice', and 'Hi, Bob'.
Click to reveal answer
intermediate
Why use template literal types with unions?
They help create precise string types that represent all valid combinations, improving type safety and autocomplete suggestions in your code.
Click to reveal answer
advanced
Can template literal types with unions be nested?
Yes, you can nest unions inside template literals multiple times to build complex string types representing many combinations.
Click to reveal answer
What does the TypeScript type `type T = `${'a' | 'b'}${'1' | '2'}`` represent?
A'a1' & 'a2' & 'b1' & 'b2'
B'a' | 'b' | '1' | '2'
CA single string 'ab12'
D'a1' | 'a2' | 'b1' | 'b2'
✗ Incorrect
The template literal with unions creates all combinations of the union members, so it results in the union of 'a1', 'a2', 'b1', and 'b2'.
Which keyword is used to combine multiple string literal types in TypeScript?
Aunion (|)
Bintersection (&)
Cextends
Dimplements
✗ Incorrect
The union operator (|) combines multiple string literal types into one union type.
Can template literal types only use string literals inside the template?
AOnly numbers can be used
BNo, any type can be used
CYes, only string literals or unions of string literals
DOnly boolean values can be used
✗ Incorrect
Template literal types work with string literals or unions of string literals to produce new string literal types.
What is the benefit of using template literal types with unions?
AThey create precise string types representing all valid combinations
BThey improve runtime performance
CThey allow dynamic string concatenation at runtime
DThey replace interfaces
✗ Incorrect
Template literal types with unions help define exact string types for better type safety and autocomplete.
If you have `type Colors = 'red' | 'blue'` and `type Shades = 'light' | 'dark'`, what does `type ColoredShade = `${Shades} ${Colors}`` produce?