惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Project Zero
Project Zero
F
Fortinet All Blogs
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
T
Tailwind CSS Blog
WordPress大学
WordPress大学
Engineering at Meta
Engineering at Meta
S
Schneier on Security
N
News and Events Feed by Topic
N
News | PayPal Newsroom
H
Help Net Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
The Exploit Database - CXSecurity.com
Attack and Defense Labs
Attack and Defense Labs
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
A
About on SuperTechFans
AWS News Blog
AWS News Blog
S
Secure Thoughts
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
C
Cybersecurity and Infrastructure Security Agency CISA
V2EX - 技术
V2EX - 技术
Recorded Future
Recorded Future
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
MyScale Blog
MyScale Blog
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
人人都是产品经理
人人都是产品经理
Latest news
Latest news
C
Cyber Attacks, Cyber Crime and Cyber Security
大猫的无限游戏
大猫的无限游戏
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
月光博客
月光博客
H
Hacker News: Front Page
P
Proofpoint News Feed
N
News and Events Feed by Topic
H
Heimdal Security Blog
L
Lohrmann on Cybersecurity
有赞技术团队
有赞技术团队
L
LangChain Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
TypeScript Template Literal Types: Turn Your Strings Into Type-Safe Contracts
Kai Thorne · 2026-06-14 · via DEV Community

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

You could use a union:

type CSSSize = "8px" | "16px" | "24px" | "100%";

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

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;
}

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" };

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;
};

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;
// }

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.