Template Literal Types

String interpolation at the type level.

TypeScript5 min readConcept 32 of 54

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>}).

Lowercase letters only
type EventName<Textendsstring> =`on${Capitalize<T>}`;

// Caller
type Handler = EventName<"click">;
Type Interpolation Engine
`onClick`
Generated Type
"onClick"

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Given `type A = 'x' | 'y'` and `type B = '1' | '2'`, what is the result of ``type C = `${A}${B}` ``?

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.