DEV Community

Kai Thorne
Kai Thorne

Posted on

TypeScript Template Literal Types: Turn Your Strings Into Type-Safe Contracts

Strings are the most common source of runtime bugs in TypeScript code. You pass "400px" where the function expects "4rem". You type "onclick" instead of "onClick". You construct a URL like /api//users because you forgot to strip a trailing slash.

Most developers solve this with runtime validation or just hope for the best. But TypeScript has a feature that lets you enforce string patterns at compile time: template literal types.

I'm not talking about basic string literal unions (type Direction = "up" | "down"). Template literal types work at a different level — they let you compose and constrain strings dynamically while keeping full type safety.

Here's what they look like in practice.

The Problem Template Literal Types Solve

Without them, this is roughly the level of safety you get:

// Both compile fine. Both can blow up at runtime.
function setSize(value: string) {
  // Is it "400px"? "4rem"? "100%"? Who knows.
}

setSize("banana"); // ✅ TypeScript sees nothing wrong
Enter fullscreen mode Exit fullscreen mode

You could use a union:

type CSSSize = "8px" | "16px" | "24px" | "100%";
Enter fullscreen mode Exit fullscreen mode

But that's useless for dynamic values. What if you need any number followed by px? You'd have to list every possible pixel value from 0 to 9999. Nobody does that.

Template literal types solve this. They let you express the shape of a string, not its exact value:

type CSSSize = `${number}px` | `${number}rem` | `${number}%` | "auto";

function setSize(value: CSSSize) {
  // ...
}

setSize("16px");   // ✅ OK
setSize("100%");   // ✅ OK
setSize("16");     // ❌ Error: missing unit
setSize("banana"); // ❌ Error: not a valid size
setSize("auto");   // ✅ OK
Enter fullscreen mode Exit fullscreen mode

No runtime overhead. No validation library. The type checker enforces the pattern.

Real Pattern 1: Type-Safe CSS Values

If you've ever worked with CSS-in-JS or a design system, you know the pain of juggling string formats:

// ❌ Bad: everything is just "string"
interface ComponentProps {
  width: string;
  height: string;
  margin: string;
  padding: string;
}
Enter fullscreen mode Exit fullscreen mode

That's not a type — it's a wish. Template literal types turn it into a contract:

type PixelValue = `${number}px`;
type PercentValue = `${number}%`;
type RemValue = `${number}rem`;

type CSSLength = PixelValue | PercentValue | RemValue | "auto" | 0;
type CSSMargin = CSSLength | `${CSSLength} ${CSSLength}`;

interface BoxProps {
  width: CSSLength;
  height: CSSLength;
  margin: CSSMargin;
  padding: CSSLength;
}

// ✅ These compile
const box1: BoxProps = { width: "400px", height: "300px", margin: "auto", padding: "24px" };
const box2: BoxProps = { width: "100%", height: "50vh" /* ❌ vh not in union */ };

// ✅ This also works — margin shorthand
const box3: BoxProps = { width: "0", height: "auto", margin: "16px 24px", padding: "8px" };
Enter fullscreen mode Exit fullscreen mode

The 0 literal (union member) is a nice touch — it means you can write width: 0 as a number instead of width: "0". TypeScript handles the number-to-string coercion at the type level.

Pitfall to watch for: number in template literal types accepts things like Infinity, NaN, and negative numbers. If you need strictly positive integers, you'll need a branded type on top. But for practical CSS work, 400px vs. -400px doesn't matter — both are valid CSS.

Real Pattern 2: Event Handler Names

Every UI library deals with event handlers. React has onClick, onChange, onMouseEnter. Vue has @click, @change. The naming convention is on + capitalized event name.

Template literal types let you express this relationship at the type level:

type EventName = "click" | "change" | "submit" | "focus" | "blur" | "mouseenter" | "mouseleave";

// Generate event handler names from event names
type EventHandler<E extends string> = `on${Capitalize<E>}`;

type ClickHandler = EventHandler<"click">;     // "onClick"
type ChangeHandler = EventHandler<"change">;   // "onChange"

// Map all events to their handlers
type AllHandlers = {
  [E in EventName as EventHandler<E>]: (event: Event) => void;
};
Enter fullscreen mode Exit fullscreen mode

This becomes genuinely useful when you're building a custom event system:

type Events = {
  click: { x: number; y: number };
  change: { value: string };
  submit: { valid: boolean };
};

// Derived handler names — single source of truth
type EventHandlers = {
  [K in keyof Events as `on${Capitalize<K & string>}`]: (payload: Events[K]) => void;
};

// ✅ EventHandlers resolves to:
// {
//   onClick: (payload: { x: number; y: number }) => void;
//   onChange: (payload: { value: string }) => void;
//   onSubmit: (payload: { valid: boolean }) => void;
// }
Enter fullscreen mode Exit fullscreen mode

The trick here is as \on${Capitalize}`— a **remapped key** in a mapped type. It takes each key, capitalizes it, and prepends "on". If you add a new event toEvents`, the handler type updates automatically.

Note: Capitalize only affects the first character. So Capitalize<"mouseenter"> becomes "Mouseenter", not "MouseEnter". For event name conventions that use full camelCase, you'd need a more sophisticated type-level transformation — or just keep event names as single words ("click", "focus", etc.) which work perfectly.

Real Pattern 3: API Route Construction

This is where template literal types really shine. API routes are just strings, but they follow strict patterns:

`typescript
type Resource = "users" | "posts" | "comments";
type Id = string; // We'll fix this
type Action = "list" | "create" | "get" | "update" | "delete";

// ❌ Without template literals
type Route = string; // No constraint at all

// ✅ With template literals
type ApiRoute = /api/${Resource} | /api/${Resource}/${string};

const route1: ApiRoute = "/api/users"; // ✅ OK
const route2: ApiRoute = "/api/posts/123"; // ✅ OK
const route3: ApiRoute = "/api/banana"; // ❌ Error
`

But you can go further. Let's make a route builder that enforces the relationship between methods and routes:

`typescript
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

type RouteDefinition = {
path: string;
method: HttpMethod;
};

// Route map: the key is "METHOD /path"
type RouteMap> = {
[K in keyof T as ${Uppercase<T[K]["method"]>} ${T[K]["path"]}]: T[K];
};
`

This is the type-level equivalent of how Express, Hono, or tRPC define routes — but enforced at compile time.

Practical: A Type-Safe Router

Let's actually build something useful — a router that extracts URL parameters from route strings:

`typescript
// Parse route params from a path string
type ExtractParams =
Path extends ${string}:${infer Param}/${infer Rest}
? { [K in Param | keyof ExtractParams]: string }
: Path extends ${string}:${infer Param}
? { [K in Param]: string }
: {};

// Define routes with typed params
type Routes = {
"/users": {};
"/users/:id": { id: string };
"/users/:id/posts": { id: string };
"/users/:id/posts/:postId": { id: string; postId: string };
};

// A helper to build URLs with the right params
function buildUrl(
path: Path,
params: ExtractParams
): string {
let url = path as string;
for (const [key, value] of Object.entries(params)) {
url = url.replace(:${key}, value as string);
}
return url;
}

// ✅ These compile
buildUrl("/users/:id", { id: "42" }); // "/users/42"
buildUrl("/users/:id/posts/:postId", { id: "42", postId: "1" }); // "/users/42/posts/1"

// ❌ These don't
buildUrl("/users/:id", {}); // Error: missing 'id'
buildUrl("/users/:id/posts/:postId", { id: "42" }); // Error: missing 'postId'
buildUrl("/users/:id/posts/:postId", { id: "42", postId: "1", extra: "x" }); // Error: extra param
`

The ExtractParams type uses infer with template literals to parse the path string. It recursively extracts :paramName segments and builds an object type. This means the type checker enforces that you provide exactly the right parameters for every route.

Important: The example above assumes all route params are strings. In a real codebase you'd want typed params (e.g. :id that's actually a number) and support for optional params and wildcards. You can extend the ExtractParams pattern with branded types or map types — the core mechanism (template literals + infer) stays the same.

Real Pattern 4: String Enum Alternatives

TypeScript enums have subtle issues (they're not a real JavaScript concept, they have runtime overhead, and numeric enums are... weird). String literal unions solve the runtime problem but don't compose well.

Template literal types let you build composed string constraints:

`typescript
type Color = "red" | "green" | "blue" | "gray";
type Intensity = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;

// Generate Tailwind-like class names
type ColorClass = ${Color}-${Intensity};
// "red-100" | "red-200" | ... | "blue-100" | ... | "gray-900"

type Spacing = "0" | "0.5" | "1" | "2" | "4" | "6" | "8";
type Direction = "t" | "b" | "l" | "r" | "x" | "y";

type TailwindPadding = p${Direction}-${Spacing} | p-${Spacing};
// "p-4" | "px-2" | "pt-8" | "pb-1" | etc.
`

A generated union like ColorClass has 36 members (4 colors × 9 intensities). If you added the full Tailwind color palette (20+ colors × 9 intensities + shades), you'd have thousands of members. TypeScript handles this fine — it's just a union of string literal types.

You can even use this for compile-time type safety:

`typescript
function className(...classes: (string | false | null | undefined)[]): string {
return classes.filter(Boolean).join(" ");
}

// Type-safe: only valid spacing values
function padding(cls: TailwindPadding) {
// ...
}

padding("p-4"); // ✅
padding("p-8"); // ✅
padding("p-12"); // ❌ Error: "12" not in Spacing union
`

Real Pattern 5: Parsing Strings with infer

The most powerful (and most confusing) use of template literal types is parsing strings at the type level using the infer keyword inside a conditional type.

`typescript
// Parse "GET /api/users" into { method: "GET", path: "/api/users" }
type ParseRoute =
R extends ${infer Method extends HttpMethod} ${infer Path}
? { method: Method; path: Path }
: never;

type GetRequest = ParseRoute<"GET /api/users">;
// { method: "GET"; path: "/api/users" }
`

This is the type-level equivalent of String.split(" "). The infer keyword tells TypeScript "figure out what goes here and give it a name." When paired with template literals, you can parse structured strings into typed objects without writing any runtime code.

Here's a more practical example — extracting query parameters from a URL string:

`typescript
type ParseQuery =
Q extends ${infer Key}=${infer Value}&${infer Rest}
? { [K in Key]: Value } & ParseQuery
: Q extends ${infer Key}=${infer Value}
? { [K in Key]: Value }
: {};

type ParseUrl =
U extends ${infer Path}?${infer Query}
? { path: Path; query: ParseQuery }
: { path: U; query: {} };

// Example
type Parsed = ParseUrl<"/api/users?page=1&limit=10">;
// {
// path: "/api/users";
// query: { page: "1"; limit: "10" };
// }
`

Reality check: Recursive conditional types with template literals have limits. TypeScript has a recursion depth of about 50 levels. For a real URL parser, you'd want to bound the query param count. But for 95% of URLs (under 10 params), this works fine.

When NOT to Use Template Literal Types

I've shown you the wins. Now the limits:

1. Don't use them for simple string unions. If you have 3 fixed values, just write a union:

`typescript
// ❌ Overkill
type Direction = ${"up" | "down" | "left" | "right"};

// ✅ Cleaner
type Direction = "up" | "down" | "left" | "right";
`

2. Don't generate combinatorially explosive unions. A template literal combining 5 sets of 100 members each creates 100^5 = 10 billion union members. TypeScript will not survive this:

`typescript
// ❌ RIP TypeScript compiler
type Everything = `${string}${string}${string}`; // Already infinite
`

3. Don't use them for runtime validation. Template literal types are compile-time only. They disappear at runtime. If you're parsing user input (API responses, form data), use a runtime validator (Zod, Valibot, ArkType).

4. Don't try to parse complex grammars. JSON, SQL, and CSS are too complex for template literal types. The infer recursion will hit depth limits fast. Use real parsers for real grammars.

Putting It All Together

Here's what a production-type-safe utility belt looks like with template literal types:

`typescript
// === CSS ===
type CSSLength = ${number}px | ${number}rem | ${number}% | ${number}vh | ${number}vw | calc(${string}) | "auto" | 0;
type CSSColor = #${string} | rgb(${number},${number},${number}) | "transparent" | "currentColor";

// === Events ===
type EventMap = {
click: MouseEvent;
change: InputEvent;
submit: SubmitEvent;
focus: FocusEvent;
blur: FocusEvent;
};
type EventHandlers = {
[K in keyof EventMap as on${Capitalize<K & string>}]: (e: EventMap[K]) => void;
};

// === API Routes ===
type ApiPath = /api/v2/${string};
type ExtractRouteParams =
R extends ${string}:${infer P}/${infer Rest}
? { [K in P | keyof ExtractRouteParams]: string }
: R extends ${string}:${infer P}
? { [K in P]: string }
: {};
`

The bottom line: Template literal types let you encode string contracts — not just string values. If your API has route patterns, your CSS has unit conventions, or your event system has naming conventions, template literal types catch mismatches before they reach production.

They're one of those features that seems gimmicky until you actually use them in a real codebase. Once you've seen TypeScript catch a mistyped route param or a missing CSS unit at compile time, going back to string-typed everything feels like programming with one hand tied behind your back.


What's your experience with template literal types? Found a clever pattern or hit a frustrating limit? Drop a comment — I'm genuinely curious what other devs are doing with them in production.

Top comments (0)