Member-only story
Mastering TypeScript Template Literal Types
How to use the awesome Template Literal Types feature

Typescript has had Template Literals since its early stages. They are really useful when you want to create types from a static string. It was not until the Typescript 4.1 release that we saw Template Literal Types. In further releases, the Typescript team has been polishing its features and fixing some quirks. As a result, it is now a mature feature.
What are Template Literal Types anyway? They are just a string literal but on steroids. You can now add a type variable to a Template Literal and Typescript will create a type with all the possible combinations for you. You can therefore compose types from others in a quick and easy way.
To make it better, Typescript now ships with some string manipulation utilities that will help you dynamically transform any string literal.
In this article, we will see how to use them and what are its use cases.
Basic usage
The Template Literals Types are used to produce any combination from strings and string types. The output will be a union string of all the possible combinations.
Let’s see a syntax example:
type attrs = "Phone" | "Name";type target = `get${attrs}`;// ✅ Result
// target = "getPhone" | "getName";
The syntax is simple yet very readable and powerful.
To better illustrate its awesomeness, let’s start by looking at an example. Let’s say we want a type that maps the CSS
padding rule type.
The code is simple: we just have to create a union of all the possible combinations:
The above code works as expected but is a bit verbose. The margin
rule is almost identical but with this approach, we won’t be able to reuse anything. We will end up with a lot of duplicated code.