0
0
Typescriptprogramming~5 mins

Template literal type syntax 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 literal strings and other string types using backticks (`) and placeholders (${...}). It works like string templates but for types.
Click to reveal answer
beginner
How do you define a template literal type that combines 'Hello' and a variable name?
You write: <br>type Greeting = `Hello, ${string}`;<br>This means Greeting can be any string starting with 'Hello, ' followed by any string.
Click to reveal answer
intermediate
Can template literal types use unions inside placeholders?
Yes! You can use unions inside placeholders to create multiple possible string types. For example:<br>type Colors = 'red' | 'blue';<br>type ColorMessage = `Color is ${Colors}`;<br>This creates 'Color is red' or 'Color is blue'.
Click to reveal answer
intermediate
What happens if you nest template literal types?
You can nest template literals to build complex string types. For example:<br>type Name = 'Alice' | 'Bob';<br>type Greeting = `Hello, ${Name}!`;<br>type ExcitedGreeting = `${Greeting} How are you?`;<br>This creates types like 'Hello, Alice! How are you?'.
Click to reveal answer
beginner
What is a practical use of template literal types?
They help create precise string types for things like event names, CSS class names, or formatted strings, improving type safety and auto-completion in code.
Click to reveal answer
Which syntax correctly defines a template literal type combining 'user_' and a number string?
Atype UserId = `user_${number}`;
Btype UserId = 'user_' + number;
Ctype UserId = `user_` & number;
Dtype UserId = 'user_' | number;
What does this type represent? <br>type Status = `status_${'success' | 'error'}`;
AAny string starting with 'status_'
B'success' or 'error'
C'status_success' or 'status_error'
D'status_' only
Can template literal types include other template literal types inside them?
ANo, nesting causes errors.
BYes, nesting is allowed.
COnly if they are the same type.
DOnly with number types.
Which of these is NOT a valid use of template literal types?
ADefining numeric ranges like `1 to 10`
BCombining string unions into formatted strings
CCreating event name types like `on${Capitalize<string>}`
DBuilding CSS class name types
What TypeScript feature allows placeholders like ${string} inside template literal types?
AType casting
BType inference
CType assertion
DType interpolation
Explain how template literal types work and give an example combining a fixed string and a union type.
Think of how string templates work but for types.
You got /3 concepts.
    Describe a practical scenario where template literal types improve code safety or developer experience.
    Consider how you might limit strings to specific patterns.
    You got /3 concepts.