Member-only story

Mastering TypeScript Template Literal Types

How to use the awesome Template Literal Types feature

Jose Granja
Better Programming
5 min readNov 9, 2021

--

Capture By Author

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";

--

--

Jose Granja
Jose Granja

Written by Jose Granja

Top Writer @Medium | 1M+ Views | Lead FE @Lingoda | I write weekly about web-development topics 📰 Support me at https://dioxmio.medium.com/membership 🙇

No responses yet

Write a response