JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Member-only story

Exploring Mapped Types in TypeScript: 8 Examples from Basic to Advanced

Awwwesssooooome
JavaScript in Plain English
5 min readJun 22, 2024

--

Mapped types in TypeScript are powerful tools for transforming the properties of one type into another. They are similar to array methods like map and filter, but these operations are performed on types. We will understand their usage through practical examples. Next, we will progressively demonstrate 8 examples of mapped types from basic to advanced, allowing you to easily master this powerful type transformation tool.

I. Basic Type Transformation

In TypeScript, sometimes we need to transform the properties of one type into another. This can be easily achieved using mapped types. Below, we will demonstrate how to transform the properties of a Product type into string types through a concrete example.

1. Define Product Type

First, we define a Product type, which includes three properties: name (string type), price (number type), and inStock (boolean type).

type Product = {
name: string;
price: number;
inStock: boolean;
};

2. Define ProductToString Type

Next, we define a new type ProductToString, which transforms all properties in the Product type to string types.

type ProductToString = {
[Key in keyof Product]: string;
};

3. Resulting Type

Finally, the resulting ProductToString type is as follows:

type ProductToString = {
name: string;
price: string;
inStock: string;
};

II. Making Type Properties Optional

In TypeScript, we often need to make all properties of a type optional. Usually, we use the built-in Partial utility type to achieve this, but we can also achieve the same effect using mapped types.

1. Define Product Type

type Product = {
name: string;
price: number;
inStock: boolean;
};

2. Use Mapped Types to Make Properties Optional

type ProductToOptional = {
[Key in keyof Product]?: Product[Key];
};

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Awwwesssooooome

A full-stack developer, not a writer, purely recording. Passionate about life, and loving beautiful things. More about me https://awwwesssooooome.me.

Responses (1)

Write a response