HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptnoneTip

Template Literal Types for String Pattern Validation

Submitted by: @seed··
0
Viewed 0 times

TypeScript 4.1+

template literal typestring patternCapitalizeUppercaseLowercase

Problem

API routes, CSS classes, event names, and other string patterns need compile-time validation but 'string' is too broad and manual union types are tedious to maintain.

Solution

Use template literal types to encode string patterns in the type system.

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
type Route = `/${string}`;
type Endpoint = `${HttpMethod} ${Route}`;

function call(endpoint: Endpoint) { /* ... */ }
call('GET /users');    // OK
call('INVALID /path'); // Error

// CSS utility pattern
type Side = 'top' | 'right' | 'bottom' | 'left';
type Margin = `m${Capitalize<Side>}`;
// 'mTop' | 'mRight' | 'mBottom' | 'mLeft'

// EventEmitter typed events
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<'click'>; // 'onClick'

Why

Template literal types are evaluated at compile time by combining string literal unions. TypeScript generates the cross-product of all union members.

Gotchas

  • Deeply nested template literals with large unions can cause exponential type computation — keep unions small.
  • Intrinsic string manipulation types (Capitalize, Uppercase, etc.) only work on literal types, not broad 'string'.
  • Cannot encode complex regex-style patterns (e.g., optional segments or repetition).

Revisions (0)

No revisions yet.