Template literal types let you build new string literal types by interpolating other types into a template — string manipulation at the type level.
ts
= ;
: = ;
: = ;
type Color = "red" | "blue";
type Shade = "light" | "dark";
type Variant = `${Shade}-${Color}`;
// "light-red" | "light-blue" | "dark-red" | "dark-blue" — all combinations
The compiler expands every combination of the unions — useful for generating valid string keys (CSS classes, event names, route patterns) automatically.
type Entity = "user" | "post";
type Event = `${Entity}:${"created" | "deleted"}`;
// "user:created" | "user:deleted" | "post:created" | "post:deleted"
function on(event: Event, cb: () => void) {}
on("user:created", () => {}); // ✅
on("user:updated", () => {}); // ❌ not a valid event
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
// { name: string } → { getName: () => string }
Uppercase, Lowercase, Capitalize, Uncapitalize are built-in intrinsic helpers.
Template literal types make string-based APIs type-safe: route params, event systems, CSS-in-JS, ORM column names.
Instead of accepting any string, you can constrain to a precise, generated set of valid strings — catching typos at compile time in places that used to be stringly-typed.