0
0
Typescriptprogramming~5 mins

Why template literal types are powerful in Typescript

Choose your learning style9 modes available
Introduction

Template literal types let you create new string types by combining other string types. This helps catch mistakes early and makes your code smarter.

When you want to build specific string patterns from smaller parts.
When you want TypeScript to check if strings follow a certain format.
When you want to create flexible but safe keys for objects.
When you want to avoid repeating similar string types manually.
When you want to improve code readability by naming complex string patterns.
Syntax
Typescript
type NewType = `${stringPart1}${stringPart2}`;

You use backticks (`) to create template literal types, similar to JavaScript template strings.

Inside the backticks, you can insert other types using ${}.

Examples
This creates a type for strings like 'Hello, Alice!' or 'Hello, Bob!'.
Typescript
type Greeting = `Hello, ${string}!`;
This type can be 'clickEvent' or 'hoverEvent' only.
Typescript
type EventName = `${'click' | 'hover'}Event`;
This type matches 'btn-primary' or 'btn-secondary'.
Typescript
type CssClass = `btn-${'primary' | 'secondary'}`;
Sample Program

This program defines a type Message that must start with 'Status: ' followed by one of the allowed statuses. The function showMessage only accepts those strings. If you try to pass a wrong string, TypeScript will show an error before running.

Typescript
type Status = 'success' | 'error' | 'loading';

type Message = `Status: ${Status}`;

function showMessage(msg: Message) {
  console.log(msg);
}

showMessage('Status: success');
// showMessage('Status: done'); // Error: Argument of type '"Status: done"' is not assignable to parameter of type 'Message'.
OutputSuccess
Important Notes

Template literal types help catch errors before running your code.

You can combine them with unions to create many string options easily.

They work only at compile time and do not affect the JavaScript output.

Summary

Template literal types build new string types by combining others.

They help TypeScript check string formats and catch mistakes early.

They make your code safer and easier to understand.