TypeScript

Creating new TypeScript types using template literal types

Advertisements

TypeScript is way more powerful than I give it credit for. I recently learned about creating new TypeScript types using template literal types, and I was pretty surprised to know that TypeScript can do that.

Let us assume we wanted to create a type for the CSS properties margin and padding, which can have sub-attributes such as top, right, left, and bottom. Instead of recreating those, we can use template literal types to achieve this

type Attribute = "margin" | "padding";
type SubAttribute = "top" | "right" | "bottom" | "left";

type MergedProperty = `${Attribute}-${SubAttribute}`;
JavaScript

and this would result in a new merged property:

type MergedProperty = "margin-top" | "margin-right" | "margin-bottom" | "margin-left" | "padding-top" |"padding-right" | "padding-bottom" | "padding-left";
JavaScript

And this helps us in creating new TypeScript types using template literal types. Pretty cool, right?

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

Share
Published by
Saransh Kataria

Recent Posts

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

4 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

5 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

5 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

6 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

7 months ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

7 months ago
Advertisements