0
0
Typescriptprogramming~20 mins

Template literal types in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Template Literal Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of Template Literal Type Concatenation
What is the type of Result after this code runs?
Typescript
type A = "Hello";
type B = "World";
type Result = `${A} ${B}!`;

// What is Result?
Astring
B"HelloWorld!"
C"Hello World"
D"Hello World!"
Attempts:
2 left
💡 Hint
Template literal types combine string literal types exactly as written.
Predict Output
intermediate
2:00remaining
Template Literal Type with Union Types
What is the type of Greeting after this code?
Typescript
type Name = "Alice" | "Bob";
type Greeting = `Hello, ${Name}!`;

// What is Greeting?
A"Hello, Alice!" | "Hello, Bob!"
B"Hello, Alice" | "Hello, Bob"
C"Hello, Alice!" & "Hello, Bob!"
Dstring
Attempts:
2 left
💡 Hint
Template literal types distribute over unions.
🔧 Debug
advanced
2:00remaining
Why does this Template Literal Type cause an error?
This code causes a TypeScript error. What is the reason?
Typescript
type Prefix = "pre";
type Suffix = number;
type Combined = `${Prefix}${Suffix}`;

// Why is this an error?
ATemplate literal types cannot concatenate two types.
BSuffix is the number type, template literal types only accept string literal types or numeric literal types.
CPrefix must be a number, not a string.
DCombined must be declared as a string, not a template literal type.
Attempts:
2 left
💡 Hint
Check the allowed types inside template literal types.
🧠 Conceptual
advanced
2:00remaining
Understanding Template Literal Type Inference
Given this function, what is the inferred return type of makeKey('user', 42)?
Typescript
function makeKey<T extends string | number, U extends string | number>(prefix: T, id: U) {
  return `${prefix}_${id}` as const;
}

const key = makeKey('user', 42);

// What is the type of key?
A`${string}_${number}`
Bstring
C"user_42"
D`${T}_${U}`
Attempts:
2 left
💡 Hint
The function uses as const to fix the return type.
Predict Output
expert
3:00remaining
Complex Template Literal Type with Conditional Types
What is the type of Result after this code?
Typescript
type Status = "success" | "error";

type Response<T extends Status> = T extends "success"
  ? `Response: ${T} with data`
  : `Response: ${T} with error`;

// What is Response<"error">?

type Result = Response<"error">;
A"Response: error with error"
B"Response: error with data"
C"Response: success with error"
D"Response: success with data"
Attempts:
2 left
💡 Hint
Conditional types choose the template based on the input type.