Strings Are a Type, Not Just a Value

A front end subscribed to order:creatd. Nothing failed, the handler simply never ran, and a week of conversion data went missing before someone noticed a flat line on a dashboard.

Template literal types let you describe patterns in strings, so the compiler knows which event names, routes and keys are valid. Below are the basics, the combinatorial explosion to watch out for (and the TS2590 error it causes), a type-safe event emitter, route parameter extraction, and the built-in intrinsic string types.

If your event names are just strings
  • Your event emitter takes a plain string for the event name and you find out about typos at runtime, in production
  • You've hand-written a route param type instead of deriving it from the actual route string, and the two have already drifted once
  • You've seen error TS2590: Expression produces a union type that is too complex to represent and worked around it by just widening everything to string
  • You want compile-time checked CSS variable names or Tailwind-style class combinations without a runtime library doing the work

Template literal types are combinatorial by nature — that's what makes them powerful and also what makes them slow tsserver down if you're not paying attention to how many unions you're multiplying together.