0
0
Typescriptprogramming~5 mins

Template literal with unions in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a template literal type in TypeScript?
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'
Which keyword is used to combine multiple string literal types in TypeScript?
Aunion (|)
Bintersection (&)
Cextends
Dimplements
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
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
If you have `type Colors = 'red' | 'blue'` and `type Shades = 'light' | 'dark'`, what does `type ColoredShade = `${Shades} ${Colors}`` produce?
A'red light' | 'blue light' | 'red dark' | 'blue dark'
B'light red' | 'light blue' | 'dark red' | 'dark blue'
C'lightred' | 'lightblue' | 'darkred' | 'darkblue'
DAn error
Explain how template literal types work with unions in TypeScript and give a simple example.
Think about how strings combine in JavaScript template literals but at the type level.
You got /4 concepts.
    Describe a practical use case where template literal types with unions improve your TypeScript code.
    Consider situations where you want to restrict strings to specific patterns.
    You got /4 concepts.