0
0
Typescriptprogramming~15 mins

Template literal types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Template Literal Types in TypeScript
📖 Scenario: You are building a small TypeScript program to create specific string types that combine fixed words with variable parts. This helps catch mistakes early by only allowing certain string patterns.
🎯 Goal: Learn how to use template literal types in TypeScript to create new string types by combining fixed and variable parts.
📋 What You'll Learn
Create a union type of colors
Create a union type of sizes
Create a template literal type combining colors and sizes
Declare a variable using the template literal type
Assign a valid value to the variable
Print the variable value
💡 Why This Matters
🌍 Real World
Template literal types help developers create precise string types that match specific patterns, reducing bugs caused by typos or invalid strings.
💼 Career
Many TypeScript projects use template literal types for safer code, especially in UI development, API design, and configuration management.
Progress0 / 4 steps
1
Create union types for colors and sizes
Create a union type called Color with the values 'red', 'green', and 'blue'. Also create a union type called Size with the values 'small', 'medium', and 'large'.
Typescript
Need a hint?

Use the | symbol to combine string literals into a union type.

2
Create a template literal type combining Color and Size
Create a template literal type called ColoredSize that combines Color and Size with a dash - between them. Use the syntax `${Color}-${Size}`.
Typescript
Need a hint?

Use backticks and ${} to create the template literal type.

3
Declare a variable using the template literal type
Declare a variable called item of type ColoredSize. Assign it the value 'green-medium'.
Typescript
Need a hint?

Use let to declare the variable and specify the type after the colon.

4
Print the variable value
Write a console.log statement to print the value of the variable item.
Typescript
Need a hint?

Use console.log(item); to print the value.