Member-only story
TypeScript 4.1’s Advanced Mapped Types
A look at recursive conditional types, template literal types, and more
If you’ve ever read any of my TypeScript articles, you’ll know that I’m a big fan of mapped types. Mapped types landed in the TypeScript version 2.1
and have seen improvements being added in every release.
They’re my all-time favorite feature because they’re fun and easy to use once you get the hang of them. If you don’t know what mapped types are, I suggest reading my previous article where I explain them in detail.
In this article, we are going to explore some of the features introduced in 4.1
and how you can apply them to mapped types.
TypeScript 4.1
TypeScript 4.1 was released recently and there are many goodies in it. In this article, we will especially focus on:
- Recursive conditional types
- Template literal types
- Key remapping in mapped types
- Checked indexed accesses
We will dive deep into those and see what new things we can do.
I strongly recommend using the TypeScript playground to best follow along with this article. You can tweak all the configurations and even switch the TypeScript version. It’s a must-use tool for newcomers, as it will also show the output of the JS code.
A Brief Refresher
Before getting into the new features, let’s do a brief recap. This will help us warm up before jumping into the new stuff.
What are mapped types?
“When you don’t want to repeat yourself, sometimes a type needs to be based on another type.
Mapped types build on the syntax for index signatures, which are used to declare the types of properties which has not been declared ahead of time.” — TypeScript’s documentation
To summarise, mapped types allow you to create new types based on existing ones. Let’s look at the Readonly
utility type as an example: