Type System

TS Mapped Types

Creating Mapped Types

TypeScript mapped types transform object properties like Readonly.

Introduction to Mapped Types

Mapped types in TypeScript allow developers to create new types by transforming properties of existing types. They are a powerful feature that can be used to change property types, make properties optional, or immutable. Mapped types are especially useful when you want to apply the same transformation to all properties of a type.

Basic Syntax of Mapped Types

The basic syntax for creating a mapped type involves using the in keyword to iterate over the keys of a given type. Consider the following syntax:

Example: Making Properties Readonly

A common use case for mapped types is to make all properties of a type readonly. This means that once a property is set, it cannot be changed. Here's how you can achieve this:

Example: Making Properties Optional

You can also use mapped types to make all properties optional. This is useful when you need a type where none of the properties are required:

Using Template Literal Types with Mapped Types

Template literal types can be combined with mapped types to create more complex types. This feature allows you to transform property keys into different formats. Here's an example:

Conclusion

Mapped types are a versatile feature in TypeScript that enable developers to transform object types with ease. Whether you're making properties optional, readonly, or altering property names, mapped types provide a powerful toolset for type transformations. As you become more familiar with them, you'll discover numerous ways to leverage their capabilities in your TypeScript projects.