Introduction to Mapped Types
Mapped types are an advanced TypeScript feature that allows you to create a new type by transforming the properties of an existing type. Instead of manually writing every property again, you can iterate over the keys of a type and change its property types, modifiers, or names.
Imagine an application that contains a User type with several properties. You might need another type where every property is optional for an update form, readonly for a configuration object, or converted to a different value type. Writing each version manually introduces duplication and makes future changes harder to maintain.
Mapped types solve this problem by generating the new structure from the original definition. They are widely useful for creating reusable type utilities, form models, API update types, validation structures, and other type transformations.
1. Understanding Mapped Type Syntax
A mapped type uses a property iteration expression such as [K in keyof T]. The keyof operator obtains the keys of a type, and the in keyword iterates over those keys to define the resulting properties.
type User = {
id: number;
name: string;
email: string;
};
type UserFlags = {
[K in keyof User]: boolean;
};
// Equivalent to:
// {
// id: boolean;
// name: boolean;
// email: boolean;
// }
In this example, TypeScript iterates over id, name, and email. Each property in the resulting type receives the type boolean, regardless of its original type.
The original User type remains unchanged. The mapped type creates a separate type whose structure is derived from User.
2. Preserving Property Types with Indexed Access
Sometimes you want to transform the modifiers of a type while keeping each property's original value type. You can achieve this with indexed access types using T[K].
type Product = {
id: number;
name: string;
price: number;
inStock: boolean;
};
type ProductCopy = {
[K in keyof Product]: Product[K];
};
The expression keyof Product identifies the available keys, while Product[K] retrieves the type associated with each current key.
As a result, ProductCopy preserves the original property names and value types. This is a useful foundation for more advanced transformations because it connects each property key to its corresponding type.
Mapped types can use the same pattern to apply changes to every property without losing the relationship between the key and its value type.
3. Creating Optional Properties
One of the most common applications of mapped types is making every property optional. This is useful for update operations where a client might provide only the fields that need to change.
type User = {
id: number;
name: string;
email: string;
};
type OptionalUser = {
[K in keyof User]?: User[K];
};
const updateUser: OptionalUser = {
name: "Abhinash"
};
The ? modifier makes each resulting property optional. The user can provide the name alone without supplying the identifier and email address.
TypeScript already provides the built-in Partial<T> utility for this pattern. The following declaration is equivalent to the custom OptionalUser definition:
type OptionalUser = Partial;
This approach is useful for patch requests, form updates, configuration overrides, and functions that accept partial data. Remember that making a property optional does not automatically make the same property nullable; null is allowed only when its type permits it.
4. Making Properties Readonly
Mapped types can add the readonly modifier to every property. This prevents ordinary assignments to those properties through a value typed with the resulting type.
type User = {
id: number;
name: string;
};
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
const user: ReadonlyUser = {
id: 101,
name: "Abhinash"
};
// Compilation error:
// user.name = "Ravi";
The resulting properties retain their original value types, but they become readonly at the type level. This is helpful when representing values that should not be reassigned through a particular reference.
TypeScript also provides the built-in Readonly<T> utility:
type ReadonlyUser = Readonly;
Be aware that readonly is a compile-time restriction and is generally shallow. It does not automatically freeze an object at runtime or make nested objects deeply readonly.
5. Adding and Removing Modifiers
Mapped types support modifier changes in both directions. You can add or remove optional and readonly modifiers depending on the requirements of the resulting type.
Adding a modifier uses ? or readonly. Removing one uses the minus prefix, such as -? or -readonly.
type User = {
readonly id: number;
name?: string;
email?: string;
};
type MutableRequired = {
-readonly [K in keyof T]-?: T[K];
};
type EditableUser = MutableRequired;
// All properties are required and mutable:
// {
// id: number;
// name: string;
// email: string;
// }
In this example, -readonly removes the readonly modifier, while -? removes optionality. The mapped type produces a required, mutable version of the original structure.
TypeScript's built-in Required<T> removes optional modifiers, and Readonly<T> adds readonly modifiers. Custom mapped types are useful when you need to combine transformations that are not represented by a single built-in utility.
6. Transforming Property Value Types
A mapped type can change the type of every property rather than simply copying the original types. For example, you may want to represent each property as a string for a reporting or display model.
type Product = {
id: number;
name: string;
price: number;
available: boolean;
};
type StringValues = {
[K in keyof T]: string;
};
type ProductDisplay = StringValues;
// {
// id: string;
// name: string;
// price: string;
// available: string;
// }
This transformation preserves the original property names but replaces every property's value type with string. It can be useful for describing formatted display values, where numbers and booleans have been converted to text.
Another option is to preserve each original type while allowing null values:
type Nullable = {
[K in keyof T]: T[K] | null;
};
type NullableProduct = Nullable;
Each property in the resulting type accepts its original value type or null. This describes the allowed values at the type level; it does not automatically assign null values to an object or change values at runtime.
7. Key Remapping with the as Keyword
TypeScript supports key remapping in mapped types. The as clause allows you to transform property names while generating a new type.
This capability is useful when creating derived property names, event-handler types, getters, setters, and API models whose naming conventions differ from their source types.
type User = {
name: string;
age: number;
};
type UserGetters = {
[K in keyof User as K extends string
? `get${Capitalize}`
: never]: () => User[K];
};
// {
// getName: () => string;
// getAge: () => number;
// }
The as expression constructs a new property name from each original key. The Capitalize utility makes the first character uppercase, and the template literal type adds the get prefix.
The K extends string check ensures that only string keys are used to construct these names. This matters because keyof can also produce numeric or symbol keys.
Key remapping was introduced in TypeScript 4.1. It enables more expressive type transformations without creating separate declarations for every generated property.
8. Filtering Properties with never
Key remapping can also remove properties from the resulting type. When a remapped key resolves to never, that property is omitted.
type User = {
id: number;
name: string;
email: string;
isActive: boolean;
};
type WithoutId = {
[K in keyof T as K extends "id" ? never : K]: T[K];
};
type PublicUser = WithoutId;
// {
// name: string;
// email: string;
// isActive: boolean;
// }
For each key, the conditional expression checks whether it matches id. If it does, the key becomes never and is removed. All other keys remain unchanged.
This technique is useful for excluding internal identifiers, removing sensitive properties from a type, or selecting properties according to a type-level rule. It is also the foundation of the built-in Omit<T, K> utility's behavior.
Type-level filtering is not a security mechanism for removing fields from actual runtime objects. If a response must not contain sensitive data, the application must also omit those values when constructing or serializing the response.
9. Selecting Properties by Their Value Types
Mapped types can inspect the value type associated with each property and retain only the keys whose values satisfy a condition. This combines key remapping, conditional types, and indexed access types.
type User = {
id: number;
name: string;
email: string;
isActive: boolean;
};
type PickByValue = {
[K in keyof T as T[K] extends ValueType
? K
: never]: T[K];
};
type StringProperties = PickByValue;
// {
// name: string;
// email: string;
// }
The expression T[K] obtains the type of the property currently being processed. The conditional type compares that property type with ValueType.
When the condition succeeds, the original key is retained. Otherwise, the key becomes never and the property is omitted.
This pattern can be adapted to select numeric properties, boolean flags, function properties, or other groups of properties. The conditional checks assignability, so a property whose type includes several possibilities is retained only when its entire property type satisfies the specified condition.
10. Understanding Built-in Mapped Utility Types
TypeScript includes several built-in utility types that rely on mapped type patterns. Using these utilities often makes application code shorter and easier to understand.
| Utility | Purpose | Example |
|---|---|---|
Partial<T> |
Makes properties optional | Partial<User> |
Required<T> |
Makes properties required | Required<User> |
Readonly<T> |
Makes properties readonly | Readonly<User> |
Pick<T, K> |
Selects specified properties | Pick<User, "name"> |
Omit<T, K> |
Excludes specified properties | Omit<User, "id"> |
Record<K, T> |
Creates properties for a key set | Record<string, number> |
For example, a user editing workflow may use the original User type to represent a complete user, Partial<User> for changes, and Pick<User, "name" | "email"> when only those properties are needed.
type User = {
id: number;
name: string;
email: string;
isActive: boolean;
};
type UserUpdate = Partial;
type UserContact = Pick;
type UserWithoutId = Omit;
type UserDirectory = Record;
These utilities cover many routine type transformations. Custom mapped types are most useful when the required behavior combines transformations or rules that built-in utilities do not directly express.
11. Common Mistakes to Avoid
-
Confusing keys with values:
keyof Trepresents property names, whileT[K]represents the type associated with a particular key. -
Forgetting property modifiers: adding
?makes properties optional, while-?removes optionality. The same principle applies toreadonly. - Expecting mapped types to change runtime values: mapped types change compile-time type definitions, not the objects stored in memory.
- Ignoring key types during remapping: template literal names usually need string keys, so guard against numeric or symbol keys when necessary.
-
Overcomplicating simple transformations: built-in utilities such as
Partial,Pick, andOmitshould be preferred when they already match the requirement. - Treating readonly as deep immutability: a readonly property does not automatically make nested objects readonly or freeze values at runtime.
12. Best Practices for Mapped Types
- Derive new types from existing models to avoid duplicating property declarations.
- Use descriptive names for custom mapped utilities so their transformation is immediately clear.
- Combine
keyofandT[K]when you need to preserve relationships between keys and value types. - Use key remapping when generating property names or filtering a type based on a rule.
- Prefer standard utility types for common operations and write custom mapped types for genuinely specialized behavior.
- Keep type-level restrictions separate from runtime validation, data transformation, and security enforcement.
Conclusion
Mapped types allow TypeScript developers to create new types by iterating over the keys of existing types. They can preserve or transform property value types, add or remove modifiers, rename properties, and filter properties using conditional types.
When combined with keyof, indexed access types, and conditional types, mapped types provide the foundation for many advanced TypeScript utilities. Learning these patterns helps reduce duplication, improve maintainability, and build strongly typed applications with less repetitive code.