The Analogy: The Lot-Code Stamp at a Cannery
A cannery stamps every tin as it leaves the line with a lot code, a short string in a strictly fixed format: a plant-line letter, a dash, the day's date digits, a dash, and a shift letter. An inspector glancing at a passing tin can say at once whether the stamp is a valid lot code or a smudge, and does so without holding a list of every code ever stamped. What the inspector knows is the shape: which segments must appear, in what order, and what each may contain. A template literal type is that shape written down for the compiler, a string built from fixed pieces of text with typed slots between them, and the compiler is the inspector checking each candidate string against the format.
The ordinary string type is the opposite of a lot code. It is the blank, unstamped tin: it will accept any mark at all, a real code, a random word, or an empty smudge, and report no complaint. A template literal type narrows that wide-open bucket down to only the strings that fit the format. The fixed pieces are literal text that must appear exactly as written, and the slots are types, each admitting only the strings that belong to that type. Where a plain string field would let a tin be stamped with the word "hello" and pass unquestioned, a template literal type rejects it because "hello" does not match the required arrangement of segments.
The real power of the format shows when the segments are drawn from lists rather than single values, because the compiler multiplies out every combination. The cannery runs three lines and two shifts, so the set of valid line-and-shift prefixes is not five but six: every line paired with every shift. When a template literal type has a slot filled by a union, the compiler produces one exact string for each member, and when two slots are unions it produces the full grid of their combinations, so two small lists become a complete, exhaustive set of allowed codes from a single line of type rather than a hand-maintained list. Alongside this the format machinery offers four case transformers, upper, lower, capitalise, and uncapitalise, which behave like the stamping head's own case-normaliser: they reshape the casing of a known literal, but they only work on a concrete literal, never on the open string bucket, because there is nothing definite to transform.
The danger, and it is the one that catches people, is mistaking a shape-check for a contents-check. The inspector confirms that a stamp has the correct form, the right segments in the right order, but form is not the same thing as truth. A tin could carry a perfectly well-formed lot code bearing a date the line never actually ran, or a numeric segment reading in an odd but technically numeric way, and the shape check would wave both through because each fits the format. A template literal type guarantees the shape of a string at compile time and says nothing whatever about whether the value is real or sensible, so anything arriving from outside the program, a code a user typed, a field read from a file, still needs a genuine runtime check. Trusting the format as though it were validation is the classic and costly error.
Syntax or Core Structure
A template literal type is written between backticks, exactly like a runtime template string, except the slots hold types rather than values and the result is the set of strings matching that shape. When the slots are filled by unions, the compiler expands every combination into a union of exact string literals.
// src/lot.ts
type Line = "A" | "B" | "C";
type Shift = "day" | "night";
// Two unions fill the slots: 3 x 2 = 6 exact codes
type Prefix = `${Line}-${Shift}`;
function makePrefix(line: Line, shift: Shift): Prefix {
return `${line}-${shift}`;
}
const p1: Prefix = makePrefix("A", "day");
const p2: Prefix = makePrefix("C", "night");
console.log(p1);
console.log(p2);
console.log(p1.length + " " + p2.length);
Output:
A-day
C-night
5 7
The type Prefix is the union of all six combinations the two unions produce, from "A-day" through "C-night", and makePrefix may only return a string that is one of them. At runtime makePrefix("A", "day") builds "A-day" and makePrefix("C", "night") builds "C-night"; a call such as makePrefix("A", "morning") would not compile because "morning" is not a member of Shift. The final line prints the two lengths: "A-day" has five characters and "C-night" has seven, giving 5 7. Two short lists became a complete grid of valid codes without a single one being written out by hand.
Technical Depth: Intrinsics, Key Remapping, and Filters
Template literal types come with four built-in case transformers and become genuinely powerful when combined with mapped types, where they let you rename or filter keys as you iterate.
The four case intrinsics
Uppercase, Lowercase, Capitalize, and Uncapitalize are compiler intrinsics: you cannot implement them yourself, and they operate only on string literal types, not on the open string. Pairing each with a generic function whose return type uses the same intrinsic keeps the value and its type in step.
// src/intrinsics.ts
function loud<S extends string>(text: S): Uppercase<S> {
return text.toUpperCase() as Uppercase<S>;
}
function title<S extends string>(text: S): Capitalize<S> {
return (text.charAt(0).toUpperCase() + text.slice(1)) as Capitalize<S>;
}
const a = loud("day"); // type "DAY"
const b = title("day"); // type "Day"
console.log(a);
console.log(b);
console.log(a.length + " " + b.length);
Output:
DAY
Day
3 3
At the type level loud("day") returns Uppercase<"day">, which is the literal type "DAY", and title("day") returns Capitalize<"day">, the literal "Day". The runtime implementations mirror the type transform exactly: toUpperCase yields "DAY" and capitalising the first character yields "Day". Both are three characters long, so the last line prints 3 3. The as cast is needed because the compiler cannot see that the runtime string operation matches the intrinsic, which is a small honesty gap worth noting.
Key remapping with as
The as clause in a mapped type renames each key as it is visited, and template literals are how you build the new name. This generates a setter method for every property of a source type.
// src/setters.ts
interface Tin {
line: string;
weight: number;
}
// A setter name per property: set + Capitalized key
type Setters<T> = {
[K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void;
};
const log: string[] = [];
const setters: Setters<Tin> = {
setLine: (value) => log.push("line=" + value),
setWeight: (value) => log.push("weight=" + value),
};
setters.setLine("A");
setters.setWeight(400);
console.log(log.length);
console.log(log.join(","));
Output:
2
line=A,weight=400
Setters<Tin> has exactly the keys setLine and setWeight, because Capitalize<"line"> is "Line" and Capitalize<"weight"> is "Weight", each prefixed with set. The odd-looking string & K is the part that matters most: keyof T can include number and symbol, and Capitalize accepts only strings, so intersecting with string narrows K down to just its string members. Calling the two generated setters pushes two entries, so the log has length 2 and reads line=A,weight=400.
Filtering keys by remapping to never
A key remapped to never is dropped from the result entirely, which turns the as clause into a filter. Combined with a template literal pattern in the condition, this keeps only the keys whose names match a shape.
// src/handlers.ts
interface Props {
id: number;
onClick: () => void;
onFocus: () => void;
}
// Keep only keys whose name starts with "on"
type Handlers<T> = {
[K in keyof T as K extends `on${string}` ? K : never]: T[K];
};
const calls: string[] = [];
const handlers: Handlers<Props> = {
onClick: () => calls.push("click"),
onFocus: () => calls.push("focus"),
};
handlers.onClick();
handlers.onFocus();
console.log(calls.length);
console.log(calls.join(","));
Output:
2
click,focus
Handlers<Props> keeps onClick and onFocus but drops id, because the condition K extends on${string}` sends any key not matching the on-prefixed shape to never, and a key mapped to never disappears. This one type combines everything from the previous lessons: a mapped type, a conditional, distribution over keyof, and never as the discard signal. Calling the two surviving handlers records two entries, giving length 2 and click,focus`.
Pattern reference
The common template-literal patterns fall into a few recurring shapes, laid out below.
| Pattern | Produces |
|---|---|
| entity then colon then action | the cross-product of two unions |
| set then Capitalized key | renamed keys in a mapped type |
| key extends on-prefixed else never | a key filter |
| double-dash then string slot | CSS custom property names |
| number slot then px | any numeric pixel value |
| api-slash then string slot | a path-prefix constraint |
Reading the shape column tells you what each pattern is for: the first row is the union cross-product that drives event names, the middle rows are the mapped-type transforms, and the last three are format constraints on a single free slot.
Real World Example: A Typed Event Tally
An application publishes events named as an entity joined to an action, and a dashboard wants a running tally per event. The event names are a template literal cross-product of two unions, so every valid name is known to the compiler and a mistyped name at a typed call site is rejected. The tally is built by dispatching a fixed sequence of events and summing a numeric field from each payload into the matching bucket, then printing one row per possible event name.
// src/events.ts
type Entity = "user" | "post";
type Action = "created" | "deleted";
// 2 x 2 = 4 exact event names
type EventName = `${Entity}:${Action}`;
interface Payload {
weight: number;
}
function pad(text: string, width: number): string {
const gap = width - text.length;
return text + " ".repeat(gap > 0 ? gap : 0);
}
const tally: Record<string, number> = {};
function dispatch(event: EventName, payload: Payload): void {
tally[event] = (tally[event] ?? 0) + payload.weight;
}
const stream: Array<{ event: EventName; payload: Payload }> = [
{ event: "user:created", payload: { weight: 10 } },
{ event: "post:created", payload: { weight: 20 } },
{ event: "user:deleted", payload: { weight: 5 } },
{ event: "user:created", payload: { weight: 3 } },
];
for (const item of stream) {
dispatch(item.event, item.payload);
}
const names: EventName[] = ["user:created", "post:created", "user:deleted", "post:deleted"];
let total = 0;
console.log("events: " + stream.length);
console.log(pad("EVENT", 15) + "TOTAL");
for (const name of names) {
const sum = tally[name] ?? 0;
total += sum;
console.log(pad(name, 15) + sum);
}
console.log("total: " + total);
Output:
events: 4
EVENT TOTAL
user:created 13
post:created 20
user:deleted 5
post:deleted 0
total: 38
Trace the stream in order. user:created arrives with weight 10, so its bucket becomes 10; post:created with 20; user:deleted with 5; and then user:created again with 3, which adds to its existing bucket for 10 + 3 = 13. Printing the four possible event names in a fixed order gives user:created at 13, post:created at 20, user:deleted at 5, and post:deleted at 0 because it never fired. The four buckets sum to 13 + 20 + 5 + 0 = 38. Iterating an explicit ordered names array rather than the object's own keys keeps the report deterministic.
The value of the template literal type is that EventName is the single source of the four valid names. Add "archived" to Action and the type instantly gains user:archived and post:archived, and any typed dispatch call using an old exhaustive list would need updating, while a call to dispatch("post:archive", ...) with a typo is rejected outright. The cross-product means the names never drift from the two source unions.
That safety has a sharp and deliberately visible flaw here: the tally is typed Record<string, number>, not Record<EventName, number>, so the moment an event name is used as an object key the compile-time guarantee is thrown away. A stray tally["user:creted"] would silently create a new bucket rather than error, exactly the mistake EventName exists to prevent, and keying the record by EventName instead would have closed the gap. Two smaller limits sit alongside: post:deleted shows 0, which is indistinguishable from an event that genuinely fired carrying a zero weight, so the report cannot tell "never happened" from "happened as zero"; and summing a weight field as the tally conflates a payload metric with an event count, so the total of 38 measures neither cleanly.
Common Mistakes
- Forgetting
string & Kbefore an intrinsic.Capitalize<K>fails to compile whenkeyof Tmay includenumberorsymbol, so the key must be narrowed to its string members first. - Expecting
Uppercase<string>to do anything. The four case intrinsics work only on string literal types; handed the openstringthey yieldstringunchanged. - Triggering a union explosion. Three unions of ten members each produce a thousand literal types, and the compiler slows sharply and eventually refuses long before that becomes useful.
- Assuming a number-shaped slot validates a number's format. Odd but technically numeric strings still satisfy a numeric template slot, so the shape check is weaker than a real numeric parse.
- Treating template literal types as runtime validation. They constrain shapes at compile time only, so any value from outside the program still needs a genuine runtime check.
- Losing a property to a
neverremap and then hunting for it. A key sent toneverin anasclause is dropped silently, which is easy to forget when the condition is subtle. - Keying a runtime record by
stringinstead of the literal union. Storing tallies under a plainstringkey discards the very compile-time safety the template literal type was created to give. - Iterating a mapped or record type with
Object.keysand expecting order. Runtime key order is not guaranteed, so a report over generated keys should walk an explicit ordered list. - Building deep recursive path types over large objects. A recursive template literal path type can blow past the compiler's instantiation depth limit on a genuinely deep or wide object.
Best Practices
- Derive string unions from data with
keyof typeof. Let oneas constobject drive both the runtime values and the type rather than writing the list twice. - Use key remapping to generate accessor shapes. A
Setters<T>or handler map from one interface beats hand-writing parallel interfaces that will drift apart. - Keep the cross-product small. Two unions is usually plenty; a third needs a clear reason because the member count multiplies.
- Name every generated type. A named
type EventName = ...makes compiler error messages read sensibly instead of dumping a giant inline union. - Narrow keys with
string & Kbefore any intrinsic. It is the idiomatic guard that keepsCapitalizeand its siblings happy over an arbitrarykeyof T. - Key runtime records by the literal union, not
string. ARecord<EventName, number>preserves at runtime the safety the template literal type gives at compile time. - Walk generated keys in an explicit order. When you must iterate a mapped or record type, a typed ordered array keeps both the order and the exhaustiveness under your control.
- Remember the boundary rule. Template literal types make your code safer, not your input safer; validate anything that crosses into the program at runtime.
Practice Exercises
- The Lot Code. Write a
Prefixtype from a line union and a shift union, confirm the compiler produces every combination, and then explain where a template literal type stops being able to enforce the date segment. - The Setters. Given an interface with four properties, generate a
Setters<T>type withset-prefixed capitalised keys, then extend it to also produce a matching set ofon-prefixed change-handler names. - The Filter. Write
Handlers<T>that keeps only the properties whose names start withonby remapping the others tonever, and confirm the resulting type has dropped every non-handler key. - The Closed Record. Build an
EventNamecross-product and aRecord<EventName, number>tally, then prove that a mistyped event key is rejected at compile time where aRecord<string, number>would have accepted it.