0
0
Typescriptprogramming~5 mins

Template literal types 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 and make your code clearer.

When you want to build specific string patterns from smaller parts.
When you want TypeScript to check if a string matches a certain format.
When you want to create flexible but safe string types for things like URLs, CSS classes, or event names.
Syntax
Typescript
type NewType = `${Prefix}${Middle}${Suffix}`;

You use backticks (`) around the template, like in JavaScript template strings.

Each part inside ${} must be a string literal type or a union of string literals.

Examples
This creates a type that can be either "Hello, World!" or "Hello, Friend!".
Typescript
type Greeting = `Hello, ${"World" | "Friend"}!`;
This type can be "onClick", "onHover", "offClick", or "offHover".
Typescript
type EventName = `${"on" | "off"}${"Click" | "Hover"}`;
This type represents CSS class names like "btn-primary", "btn-secondary", or "btn-danger".
Typescript
type CssClass = `btn-${"primary" | "secondary" | "danger"}`;
Sample Program

This program defines a type Status with three possible values. Then it creates a template literal type Message that combines a fixed string with Status. The function showMessage only accepts strings matching the Message type. Trying to pass a wrong string causes an error.

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

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

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

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

Template literal types only work with string literal types, not general strings.

They help catch errors early by limiting allowed string values.

You can combine them with unions to create many possible string patterns.

Summary

Template literal types build new string types by combining smaller string types.

They help TypeScript check if strings match specific patterns.

Use them to make your code safer and clearer when working with strings.