How to use Template Literal Types in TypeScript

In this article, let's learn how to use Template Literal Types in TypeScript.

This should be intuitive if you are used to using template literals in JavaScript. But to ensure we are on the same page,

A template literal is an easy way to concatenate strings in JavaScript. Instead of using the + operator, you can use backticks (``) and ${} to embed expressions within a string:

const name = "Niall";
console.log(`Hello, ${name}!`);
// Logs: Hello, Niall!

Easy, right?

The fun part is we can use template literals in types! This means you can now create types by concatenating strings with template literals.

Code Time

I always find these things easier to understand with context, so let’s dive into an example:

Imagine you’re building a library like Tailwind with many different color and number combinations:

type RedColorNumber = "red-50" | "red-100" | "red-200" | "red-300"; // … all the way to red-950

What happens when we want to add another ten colors and possibly more numbers?

It could get very tedious very fast...

This is where Template Literal Types in TypeScript save the day by allowing you to create combinations of types easily.

Let's see how you can make this much more dynamic:

type Color = "red" | "blue" | "green";
type Number = "50" | "100" | "200" | "300" | "400" | "500";
type ColorNumber = `${Color}-${Number}`;

Now in ColorNumber type will auto-magically be something like "red-50", "blue-200", "green-400" or any other combination of our types.

Cool right?

Now it’s your turn to try out Template Literal Types in TypeScript.

Happy coding! 🎉

TsTypeScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.