Typescript Foundations / Advanced Types

Template Literal Types

Template Literal Types allow you to create new string literal types by embedding expressions into string templates.

🧱 Syntax:

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

This allows you to enforce or construct types that follow specific patterns.


✅ Basic Example

type Color = "red" | "green" | "blue";
type BrightColor = `bright-${Color}`;

// BrightColor = "bright-red" | "bright-green" | "bright-blue"

🔠 Capitalize, Lowercase, Uppercase, Uncapitalize

TypeScript offers built-in string manipulation types to use within templates.

type Fruit = "apple" | "banana";
type CapitalFruits = Capitalize<Fruit>; // "Apple" | "Banana"

type Msg = `You chose ${Capitalize<Fruit>}`;
// "You chose Apple" | "You chose Banana"

🧠 Combine with Unions

type Sizes = "S" | "M" | "L";
type Variants = "primary" | "secondary";

type ButtonClass = `${Variants}-${Lowercase<Sizes>}`;
// "primary-s" | "primary-m" | "primary-l" | "secondary-s" | ...

🔁 Dynamic Key Creation in Mapped Types

Template literal types are especially useful with mapped types:

type Events = "click" | "focus";
type EventHandlers = {
  [K in Events as `on${Capitalize<K>}`]: () => void;
};

// EventHandlers:
// {
//   onClick: () => void;
//   onFocus: () => void;
// }

🧪 Use Case: CSS Classes

type Position = "top" | "bottom" | "left" | "right";
type Offset = "0" | "1" | "2";

type MarginClasses = `m-${Position}-${Offset}`;
// e.g., "m-top-0" | "m-bottom-1" | ...


📌 Summary

Feature

Example

Template literal type

User-${string}

Combine with union types

`error-${"404"

Capitalize/Uncapitalize

Hi ${Capitalize<"world">}

Use with mapped types

on${Capitalize}


Template literal types give you more control over string structures at the type level. They’re heavily used in libraries like Tailwind, GraphQL, tRPC, and design systems for enforcing patterns.