๐—ง๐˜†๐—ฝ๐—ฒ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜ ๐—ง๐—ฒ๐—บ๐—ฝ๐—น๐—ฎ๐˜๐—ฒ ๐—Ÿ๐—ถ๐˜๐—ฒ๐—ฟ๐—ฎ๐—น ๐—ง๐˜†๐—ฝ๐—ฒ๐˜€

Strings cause many bugs in TypeScript.

You might pass "400px" when a function needs "4rem". You might type "onclick" instead of "onClick". You might build a broken URL because of a trailing slash.

Most developers use runtime validation or hope for the best. You can do better. Template literal types let you enforce string patterns during development.

These types let you compose and constrain strings dynamically. They keep your code safe without adding runtime overhead.

Use them for CSS units:

With this, "16px" works. "16" fails because it misses the unit. "banana" fails because it is not a size.

Use them for event handlers:

If you have an event named "click", TypeScript generates "onClick". If you add a new event to your system, the handler updates automatically.

Use them for API routes:

This ensures your routes follow a strict structure. You can even use the infer keyword to extract URL parameters from a path string at compile time.

When to avoid them:

Template literal types turn strings into contracts. They catch mistakes before they reach your users.

Source: https://dev.to/kaithorne/typescript-template-literal-types-turn-your-strings-into-type-safe-contracts-529f