TypeScript

Template Literal Types

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Build string types out of other string types. Lets you express patterns like "every CSS event handler starts with on" in the type system itself, with autocomplete to match.
TypeScript
Raw
type EventName<K extends string> = `on${Capitalize<K>}`;

type ClickHandler = EventName<'click'>;   // 'onClick'
type FocusHandler = EventName<'focus'>;   // 'onFocus'

// Strongly-typed CSS variable names
type CssVar<K extends string> = `--${K}`;
const setVar = <K extends string>(el: HTMLElement, k: K, v: string) =>
  el.style.setProperty(`--${k}` as CssVar<K>, v);

// Parse "GET /users/:id" → "GET" + "/users/:id"
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Route<M extends Method, P extends string> = `${M} ${P}`;

const handle = (r: Route<'GET', '/users/:id'>) => {};
handle('GET /users/:id');     // ✓
handle('POST /users/:id');    // ✗
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.