Bird
Raised Fist0
Typescriptprogramming~10 mins

Template literal types in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Template literal types
Define base string types
↓
Create template literal type
↓
Use template literal type in variables
↓
TypeScript checks if values match pattern
↓
Accept or error based on pattern match
Template literal types combine string types with placeholders to create new string patterns that TypeScript can check.
Execution Sample
Typescript
type Greeting = `Hello, ${string}!`;

const greet1: Greeting = "Hello, Alice!";
const greet2: Greeting = "Hello, Bob!";
const greet3: Greeting = "Hi, Charlie!"; // Error
This code defines a template literal type Greeting and assigns strings matching or not matching the pattern.
Execution Table
StepActionValue CheckedType Check ResultNotes
1Define Greeting type`Hello, ${string}!`Type createdTemplate literal type expects strings starting with 'Hello, ' and ending with '!'
2Assign greet1"Hello, Alice!"PassMatches pattern exactly
3Assign greet2"Hello, Bob!"PassMatches pattern exactly
4Assign greet3"Hi, Charlie!"FailDoes not start with 'Hello, ' so error
💡 TypeScript stops checking after error on greet3 assignment due to pattern mismatch
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4
greet1undefined"Hello, Alice!""Hello, Alice!""Hello, Alice!"
greet2undefinedundefined"Hello, Bob!""Hello, Bob!"
greet3undefinedundefinedundefinedError - invalid assignment
Key Moments - 2 Insights
Why does assigning "Hi, Charlie!" to Greeting cause an error?
Because the template literal type Greeting requires the string to start with "Hello, " and end with "!". "Hi, Charlie!" does not match this pattern, as shown in execution_table row 4.
Can template literal types include any string inside the placeholder?
Yes, the ${string} placeholder means any string can appear there, but the surrounding fixed parts must match exactly, as seen in the Greeting type definition and assignments.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the type check result for greet2 assignment?
AFail
BError
CPass
DNot checked
💡 Hint
Check execution_table row 3 under 'Type Check Result'
At which step does the type check fail due to pattern mismatch?
AStep 2
BStep 4
CStep 3
DNo failure
💡 Hint
See execution_table row 4 'Type Check Result' column
If we change Greeting to `Hi, ${string}!`, what happens to greet3 assignment?
AIt passes type check
BIt still fails
CIt causes a syntax error
DIt becomes optional
💡 Hint
Consider how template literal type pattern matches string values in variable_tracker
Concept Snapshot
Template literal types combine fixed strings and placeholders.
Syntax: type NewType = `prefix${string}suffix`;
Variables must match the pattern exactly.
TypeScript checks assignments against this pattern.
Useful for enforcing string formats at compile time.
Full Transcript
Template literal types in TypeScript let you create new string types by combining fixed parts and placeholders. For example, type Greeting = `Hello, ${string}!` means any string starting with 'Hello, ' and ending with '!'. When you assign a value to a variable of this type, TypeScript checks if the string matches the pattern. If it does, the assignment passes; if not, it causes a type error. This helps catch mistakes early by enforcing string formats. In the example, 'Hello, Alice!' and 'Hello, Bob!' pass, but 'Hi, Charlie!' fails because it doesn't start with 'Hello, '. Changing the template literal type changes which strings are accepted.

Practice

(1/5)
1. What is the main purpose of template literal types in TypeScript?
easy
A. To create new string types by combining existing string types
B. To perform string concatenation at runtime
C. To define numeric ranges for variables
D. To declare functions with string parameters

Solution

  1. Step 1: Understand template literal types

    Template literal types allow combining string literal types to form new string types.
  2. Step 2: Differentiate from runtime string operations

    They are used at compile time for type checking, not for runtime string concatenation or numeric ranges.
  3. Final Answer:

    To create new string types by combining existing string types -> Option A
  4. Quick Check:

    Template literal types build new string types [OK]
Hint: Remember: template literal types create types, not runtime strings [OK]
Common Mistakes:
  • Confusing template literal types with runtime string concatenation
  • Thinking they define numeric ranges
  • Assuming they declare functions
2. Which of the following is the correct syntax to define a template literal type combining 'hello' and 'world' with a space in between?
easy
A. type Greeting = `${'hello'} ${'world'}`;
B. type Greeting = `hello world`;
C. type Greeting = `${'hello' + ' ' + 'world'}`;
D. type Greeting = '${hello} ${world}';

Solution

  1. Step 1: Understand template literal syntax

    Template literal types use backticks and ${} to embed string literals or types.
  2. Step 2: Check each option

    type Greeting = `${'hello'} ${'world'}`; correctly uses backticks and embeds 'hello' and 'world' with a space between them. type Greeting = `${'hello' + ' ' + 'world'}`; uses + inside template literal which is invalid. type Greeting = `hello world`; is a plain string literal, not combining types. type Greeting = '${hello} ${world}'; uses single quotes and incorrect syntax.
  3. Final Answer:

    type Greeting = `${'hello'} ${'world'}`; -> Option A
  4. Quick Check:

    Correct template literal syntax uses backticks and ${} [OK]
Hint: Use backticks and ${} to embed strings in template literal types [OK]
Common Mistakes:
  • Using + inside template literals
  • Using single quotes instead of backticks
  • Writing plain strings instead of template literal types
3. Given the following TypeScript code, what is the type of greeting?
type Hello = 'hello';
type World = 'world';
type Greeting = `${Hello} ${World}`;

const greeting: Greeting = 'hello world';
medium
A. `${Hello}${World}`
B. 'hello' | 'world'
C. string
D. 'hello world'

Solution

  1. Step 1: Understand the template literal type definition

    The type Greeting combines 'hello' and 'world' with a space, so it represents the exact string 'hello world'.
  2. Step 2: Check the assigned value type

    The variable greeting is assigned 'hello world', which matches the Greeting type exactly.
  3. Final Answer:

    'hello world' -> Option D
  4. Quick Check:

    Template literal type matches exact combined string [OK]
Hint: Template literal types produce exact combined string types [OK]
Common Mistakes:
  • Thinking the type is a union of 'hello' and 'world'
  • Assuming it is a generic string
  • Confusing the template literal syntax with a string literal
4. Identify the error in the following TypeScript code using template literal types:
type Prefix = 'pre';
type Suffix = 'fix';
type Combined = `${Prefix + Suffix}`;

const word: Combined = 'prefix';
medium
A. Missing backticks around the template literal
B. The variable word has wrong value assigned
C. Using + operator inside template literal types is invalid
D. Prefix and Suffix types must be numbers

Solution

  1. Step 1: Check template literal syntax

    Inside template literal types, you cannot use the + operator to concatenate types; you embed types directly with ${}.
  2. Step 2: Identify the error

    The expression `${Prefix + Suffix}` is invalid syntax. It should be `${Prefix}${Suffix}` without +.
  3. Final Answer:

    Using + operator inside template literal types is invalid -> Option C
  4. Quick Check:

    Template literal types concatenate by adjacent ${} without + [OK]
Hint: No + inside template literal types; just place ${} side by side [OK]
Common Mistakes:
  • Using + operator inside template literal types
  • Confusing runtime string concatenation with type syntax
  • Assuming types must be numbers to concatenate
5. You want to create a type EventName that represents strings like 'click_button' or 'hover_link' by combining event types 'click' | 'hover' and target types 'button' | 'link' separated by an underscore. Which of the following correctly defines EventName?
hard
A. type EventName = `${click | hover}_${button | link}`;
B. type EventName = `${'click' | 'hover'}_${'button' | 'link'}`;
C. type EventName = `${'click' & 'hover'}_${'button' & 'link'}`;
D. type EventName = '${click | hover}_${button | link}';

Solution

  1. Step 1: Understand union types in template literals

    Using union types inside ${} creates all combinations of the union members.
  2. Step 2: Check syntax correctness

    type EventName = `${'click' | 'hover'}_${'button' | 'link'}`; correctly uses backticks and unions inside ${} with an underscore between them. type EventName = '${click | hover}_${button | link}'; uses single quotes and invalid syntax. type EventName = `${'click' & 'hover'}_${'button' & 'link'}`; uses & which means intersection, not union, so it won't produce combinations. type EventName = `${click | hover}_${button | link}`; misses quotes around string literals.
  3. Final Answer:

    type EventName = `${'click' | 'hover'}_${'button' | 'link'}`; -> Option B
  4. Quick Check:

    Union types inside template literals create all string combinations [OK]
Hint: Use unions inside ${} with backticks to create all string combos [OK]
Common Mistakes:
  • Using & instead of | for unions
  • Omitting quotes around string literals
  • Using single quotes instead of backticks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard