Course contentsShow
← TypeScript
Lesson 818 of 1,79619. Template Literal TypesFree lesson

What Are Template Literal Types?

Template literal types use backtick syntax to create types from string patterns, similar to template literals in JavaScript.

What Are Template Literal Types?

You'll learn: How TypeScript lets you create types from string patterns using backtick syntax, just like JavaScript template literals.

The Core Idea

Template literal types use the familiar backtick (`) syntax to construct new string types by combining and interpolating other types. Just as JavaScript template literals let you build strings dynamically, template literal types let you build type definitions dynamically.

Think of them as "type-level string builders." You're not creating actual string values—you're defining the shape of strings your program can accept or produce.

How They Look

The syntax mirrors JavaScript template literals, but lives entirely in the type world:

type Greeting = `Hello, ${string}`;

// ✅ These types match the pattern:
const msg1: Greeting = "Hello, TypeScript";
const msg2: Greeting = "Hello, World";

// ❌ This doesn't match:
// const msg3: Greeting = "Hi there";

The ${string} interpolation says "any string can go here," but the type must start with "Hello, ".

Why They Matter

Before template literal types, creating precise string patterns required long union types or gave up type safety entirely. Now you can encode string conventions directly into the type system—like CSS property names, URL patterns, or event names—and get full autocompletion and error checking.

An Analogy

If types are contracts about what values look like, template literal types are like Mad Libs contracts: "This value must be a string that says ___ followed by a dash, then ___." The blanks get filled with other types, and TypeScript enforces the pattern.

Key Takeaway: Template literal types use backtick syntax to create type-safe string patterns by combining static text with type interpolations, enabling precise modeling of string-based conventions at the type level.