Template Literal Types
String interpolation at the type level.
Types that build Strings
Template Literal Types build on string literal types, allowing you to interpolate other types into a string via backticks.
Just like JavaScript string interpolation (Hello ${name}), but entirely within the type system!
Combinatorial Explosion
If you are building a CSS or UI library, you might need hundreds of specific string combinations, like margin-top-sm or border-red-500.
Instead of writing them all out manually, you can provide unions to a template literal type, and TypeScript will automatically generate every possible combination.
Syntax
typescript
type Color = "red" | "blue";
type Size = "sm" | "lg";
// TypeScript generates all 4 combinations automatically!
type ClassName = text-${Color}-${Size};
// "text-red-sm" | "text-red-lg" | "text-blue-sm" | "text-blue-lg"
// You can also use intrinsic string manipulation types
type EventName<T extends string> = on${Capitalize<T>};
type ClickEvent = EventName<"click">; // "onClick"
Try it
Type an event string in the input and watch the interpolation logic dynamically generate the properly cased handler name (e.g. on${Capitalize<Event>}).
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Template literal types use backticks and
${}interpolation. - Interpolating union types automatically generates every possible combination.
- They are incredibly powerful for typing dynamic string paths, CSS classes, and event names.
- Be careful of combinatorial explosion slowing down your compiler.
Done with this concept?
Mark it complete to track your progress. No login needed.