What Are Template Literal Types in TypeScript?

Learn What Are Template Literal Types in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Template Literal Types

Template literal types are a TypeScript feature that allows you to construct new string types from existing types. They use syntax similar to JavaScript template literals, but instead of generating strings at runtime, they describe which string values are permitted during compilation.

Imagine that an application supports several events, API routes, CSS properties, or configuration keys. Instead of manually listing every possible string, you can combine existing string literal types to generate the allowed values automatically.

Template literal types are especially useful for event systems, type-safe routing, naming conventions, generated property names, and reusable libraries. When combined with union types, generics, mapped types, and conditional types, they provide a powerful way to make string-based APIs safer and easier to maintain.

1. Understanding the Basic Syntax

A template literal type uses backticks and the interpolation syntax ${Type}. The expression inside the interpolation represents a type whose possible values are incorporated into the resulting string type.

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

const message1: Greeting = "Hello, Abhinash";
const message2: Greeting = "Hello, Developer";

// Compilation error:
// const message3: Greeting = "Welcome, Abhinash";

The type `Hello, ${string}` accepts strings that begin with Hello, followed by any string value. The prefix must match, so a string beginning with Welcome, is not assignable to this type.

Unlike a normal JavaScript template literal, this expression does not produce a string value. It creates a type describing the accepted string pattern.

2. Combining String Literal Types

One of the most useful features of template literal types is their ability to combine unions. If an interpolated type contains several possible literal values, TypeScript generates the combinations allowed by those values.

type Color = "red" | "blue";
type Position = "left" | "right";

type ColorPosition = `${Color}-${Position}`;

// Result:
// "red-left"
// "red-right"
// "blue-left"
// "blue-right"

const position1: ColorPosition = "red-left";
const position2: ColorPosition = "blue-right";

In this example, both Color and Position contain two possible values. Combining them produces four possible string literal types.

When multiple interpolated positions contain unions, TypeScript combines the possible values across those positions. This can reduce repetitive declarations, but be aware that the number of generated combinations can grow rapidly when the unions are large.

3. Generating Type-Safe Event Names

Template literal types are particularly useful when event names follow a consistent naming convention. Instead of accepting arbitrary strings, you can derive valid event names from an existing object type.

type User = {
  name: string;
  age: number;
  isActive: boolean;
};

type ChangedEvent = `${string & keyof User}Changed`;

const event1: ChangedEvent = "nameChanged";
const event2: ChangedEvent = "ageChanged";

// Compilation error:
// const event3: ChangedEvent = "emailChanged";

The expression keyof User produces the keys of the User type. Interpolating those keys into the template literal constructs an event name for each valid property.

Here, the string & expression constrains the interpolated key to string-compatible values. This is useful for generic object types where keys could also be numbers or symbols.

A more advanced implementation can connect each event name to its corresponding property value type. This lets event handlers receive the correct value type for the property that changed.

type PropEventSource = {
  on(
    event: `${K}Changed`,
    callback: (value: T[K]) => void
  ): void;
};

declare function watchUser(
  user: T
): PropEventSource;

const user = {
  name: "Abhinash",
  age: 27
};

const watcher = watchUser(user);

watcher.on("nameChanged", value => {
  console.log(value.toUpperCase());
});

watcher.on("ageChanged", value => {
  console.log(value.toFixed(0));
});

In this example, TypeScript infers the property key from the event name and uses T[K] to determine the callback's value type. The callback receives a string for nameChanged and a number for ageChanged.

The declare keyword describes a function signature for type checking; it does not provide a runtime implementation. In a real application, you must implement the event source separately.

4. Creating Type-Safe API Routes

Template literal types can define route patterns for applications that use consistent URL structures. This helps prevent mistakes when route names are constructed from identifiers or predefined resource names.

type Resource = "users" | "products" | "orders";

type ApiRoute = `/api/${Resource}`;

const usersRoute: ApiRoute = "/api/users";
const productsRoute: ApiRoute = "/api/products";

// Compilation error:
// const invalidRoute: ApiRoute = "/api/customers";

The ApiRoute type permits only the routes generated from the Resource union. When a new resource is added to the union, the corresponding route becomes available automatically.

You can also define routes that contain numeric identifiers:

type UserDetailRoute = `/api/users/${number}`;

const userRoute1: UserDetailRoute = "/api/users/101";
const userRoute2: UserDetailRoute = "/api/users/250";

// Compilation error:
// const userRoute3: UserDetailRoute = "/api/users/abc";

The number interpolation constrains the embedded portion to TypeScript's numeric template-literal pattern. This provides useful compile-time checks, but it is not a complete URL validator or a guarantee that a requested resource exists.

5. Using Built-In String Manipulation Types

TypeScript provides intrinsic string manipulation types that transform string literal types. These utilities are frequently combined with template literal types to generate naming conventions.

Utility Purpose Example result
Uppercase<T> Converts characters to uppercase "HELLO"
Lowercase<T> Converts characters to lowercase "hello"
Capitalize<T> Capitalizes the first character "Hello"
Uncapitalize<T> Lowercases the first character "hello"

These utilities operate on string types during compilation. They do not call JavaScript string methods at runtime.

type Action = "save" | "delete";

type UppercaseAction = Uppercase;
// "SAVE" | "DELETE"

type HandlerName = `on${Capitalize}`;
// "onSave" | "onDelete"

type LowercaseAction = Lowercase<"CREATE_USER">;
// "create_user"

These transformations are helpful for defining event handler names, command types, constants, and APIs that follow predictable string conventions.

6. Combining Template Literal Types with Mapped Types

Mapped types iterate over properties, while template literal types can generate new property names. Combining the two allows you to create related types automatically.

type User = {
  name: string;
  age: number;
};

type GetterMethods = {
  [K in keyof T as K extends string
    ? `get${Capitalize}`
    : never]: () => T[K];
};

type UserGetters = GetterMethods;

// Result:
// {
//   getName: () => string;
//   getAge: () => number;
// }

The mapped type iterates over every key in T. The as clause transforms each string key into a new key, and T[K] preserves the value type associated with the original property.

This pattern can be adapted to generate setter methods, event handlers, validation functions, or other property-related APIs. It is particularly valuable in reusable libraries where generated types must stay synchronized with changing models.

7. Pattern Matching with infer

Template literal types can be combined with conditional types and the infer keyword to extract parts of a string literal type. This technique is useful when working with naming conventions, route patterns, prefixes, and suffixes.

type ExtractPrefix =
  T extends `${infer Prefix}-${string}`
    ? Prefix
    : never;

type First = ExtractPrefix<"user-created">;
// "user"

type Second = ExtractPrefix<"order-updated">;
// "order"

type Invalid = ExtractPrefix<"notification">;
// never

TypeScript attempts to match the input against the template pattern. The infer Prefix variable captures the portion before the first hyphen that satisfies the pattern.

When the input does not match the required structure, the conditional type selects never. This makes it possible to create utilities that accept only strings following a specified convention.

You can use similar patterns to remove prefixes, extract suffixes, separate route segments, or derive information from event names. For complex string parsing, carefully test the behavior with empty segments, multiple delimiters, and unions of literal strings.

8. Creating Type-Safe Event Handler Names

An application may expose callbacks using event names such as onClick, onSubmit, or onChange. Template literal types and capitalization utilities can derive these names from a smaller set of event definitions.

type EventName = "click" | "submit" | "change";

type HandlerName =
  `on${Capitalize}`;

// "onClick" | "onSubmit" | "onChange"

const clickHandler: HandlerName = "onClick";
const submitHandler: HandlerName = "onSubmit";

The original union describes event names in lowercase. The template literal type and Capitalize generate a corresponding union of handler names.

This pattern reduces duplication between event names and handler naming conventions. If a new event is added to the original union, the corresponding handler name becomes available without manually updating another list.

9. Understanding Limitations and Performance

Template literal types are powerful, but they work with compile-time types rather than arbitrary runtime strings. TypeScript can check a literal string against a known template pattern, but it cannot automatically determine the exact literal value of every string produced while a program runs.

For example, a general string variable cannot automatically be treated as one of a small set of literal values merely because its runtime content might match that set. A type assertion or validation function should only be used when its guarantees are justified.

type Status = "pending" | "approved";

const input: string = getStatusFromApi();

// Type error: string is not assignable to Status.
// const status: Status = input;

function isStatus(value: string): value is Status {
  return value === "pending" || value === "approved";
}

function getStatusFromApi(): string {
  return "pending";
}

const status: Status | undefined =
  isStatus(input) ? input : undefined;

In this example, a runtime validation function checks the incoming value before narrowing it to the Status union. Template literal types provide compile-time guarantees; validating external values requires runtime checks.

Another consideration is the number of possible generated strings. Combining several large unions can create a very large set of combinations, increasing type-checking work or exceeding compiler limits. Keep generated string patterns focused and avoid unnecessarily large unions when a broader string type is sufficient.

10. Common Mistakes to Avoid

  • Confusing value interpolation with type interpolation: JavaScript template literals create strings at runtime, while template literal types describe valid string types during compilation.
  • Expecting arbitrary strings to satisfy a narrow pattern: a general string type is not automatically assignable to a specific string literal union or template pattern.
  • Forgetting union expansion: interpolation can generate combinations from multiple unions, potentially producing more possibilities than expected.
  • Assuming string utility types change runtime data: Uppercase, Lowercase, and related utilities transform types, not actual string variables.
  • Using types as runtime validation: API values, form inputs, and other external strings still require runtime validation when their contents must meet a particular format.
  • Creating unnecessarily complex patterns: deeply nested template literal types can make errors harder to interpret and increase compiler workload.

11. Best Practices for Template Literal Types

  • Use template literal types when strings follow predictable naming conventions or patterns.
  • Derive names from existing unions instead of maintaining multiple lists of related strings.
  • Combine keyof, mapped types, and indexed access types to generate property-specific APIs.
  • Use the built-in string manipulation types for common capitalization and case transformations.
  • Keep runtime validation separate from type-level constraints when data comes from external sources.
  • Test patterns against valid values, invalid values, unions, and edge cases involving delimiters.
  • Avoid generating extremely large combinations when a simpler type provides adequate safety.

Conclusion

Template literal types allow TypeScript developers to construct precise string types from literal values, unions, and generic types. They help enforce naming conventions, generate event names, describe API routes, and extract string segments using conditional types and inference.

When combined with mapped types, keyof, and the built-in string manipulation utilities, template literal types reduce repetitive declarations and keep related APIs consistent. Understanding their compile-time behavior and limitations helps you build more expressive and reliable TypeScript applications.

Code Examples

Create Template Literal Types

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

const first: Greeting = "Hello, Developer";
const second: Greeting = "Hello, Abhinash";

// Compilation error:
// const invalid: Greeting = "Welcome, Developer";
    

Combine Union Types

typescript
type Color = "red" | "blue";
type Position = "left" | "right";

type ColorPosition = `${Color}-${Position}`;

const first: ColorPosition = "red-left";
const second: ColorPosition = "blue-right";
    

Generate Event Names from Object Keys

typescript
type User = {
  name: string;
  age: number;
};

type ChangedEvent = `${string & keyof User}Changed`;

const nameEvent: ChangedEvent = "nameChanged";
const ageEvent: ChangedEvent = "ageChanged";

// Compilation error:
// const emailEvent: ChangedEvent = "emailChanged";
    

Transform String Literal Types

typescript
type Action = "save" | "delete";

type UppercaseAction = Uppercase<Action>;
// "SAVE" | "DELETE"

type HandlerName = `on${Capitalize<Action>}`;
// "onSave" | "onDelete"

const handler: HandlerName = "onSave";
    

Extract a String Prefix

typescript
type ExtractPrefix<T> =
  T extends `${infer Prefix}-${string}`
    ? Prefix
    : never;

type First = ExtractPrefix<"user-created">;
// "user"

type Second = ExtractPrefix<"order-updated">;
// "order"

type Invalid = ExtractPrefix<"notification">;
// never
    

Generate Getter Names with Mapped Types

typescript
type User = {
  name: string;
  age: number;
};

type GetterMethods<T> = {
  [K in keyof T as K extends string
    ? `get${Capitalize<K>}`
    : never]: () => T[K];
};

type UserGetters = GetterMethods<User>;

// {
//   getName: () => string;
//   getAge: () => number;
// }
    

Pro Tip

Derive string patterns from existing unions or object keys instead of maintaining duplicate string lists. Combining template literal types with keyof, mapped types, and indexed access keeps generated event names and handler types synchronized with your data models. Validate external strings at runtime before treating them as trusted literal types.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.