TypeScript Mapped Types
Learn how to create new types by transforming existing properties using keyof, indexed access types, mapping modifiers and key remapping.
1. What are Mapped Types?
Mapped Types are a TypeScript feature that creates a new type by transforming the properties of an existing type. Instead of defining every property manually, we can iterate over the original type's keys.
The keyof operator gets the keys of a type, while
[K in keyof T] maps over those keys.
Basic Syntax
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
interface Student {
id: number;
name: string;
age: number;
}
type ReadonlyStudent = MyReadonly<Student>;
const student1: ReadonlyStudent = {
id: 101,
name: "Rahul",
age: 22
};
console.log(student1.name);
console.log(student1.age);
// This would cause a TypeScript error:
// student1.age = 23;
Expected Output
Rahul
22
The mapped type creates a new type with the same properties as Student, but each property becomes readonly.
2. Mapped Types Workflow Diagram
Follow this workflow to understand how TypeScript transforms the properties of an existing type.
Existing Type
Define properties and their types in an interface or type alias.
Get Keys
Use keyof to obtain the available property keys.
Map Properties
Transform properties using mapped type syntax.
New Type
Use the transformed type in your application.
3. Understanding keyof
The keyof operator creates a union of the keys
of an object type. Mapped Types use these keys to determine
which properties to transform.
Example
interface Employee {
id: number;
name: string;
department: string;
}
type EmployeeKeys = keyof Employee;
const key1: EmployeeKeys = "id";
const key2: EmployeeKeys = "name";
const key3: EmployeeKeys = "department";
console.log(key1);
console.log(key2);
console.log(key3);
// This would cause a TypeScript error:
// const key4: EmployeeKeys = "salary";
Expected Output
id
name
department
EmployeeKeys becomes the type
"id" | "name" | "department".
Other property names are not accepted by this type.
4. Creating a Mapped Type
A mapped type uses [K in keyof T] to iterate through
every key in T. The expression T[K] represents the
type of the current property.
Example: Optional Properties
interface Product {
id: number;
name: string;
price: number;
}
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type OptionalProduct = MyPartial<Product>;
const product1: OptionalProduct = {
name: "Keyboard"
};
console.log(product1.name);
console.log(product1.price);
Expected Output
Keyboard
undefined
How the Mapping Works
Product
id, name and price are initially required.
MyPartial
Maps each property and adds the optional marker.
OptionalProduct
Any property can be omitted from the object.
Partial<T> utility type.
5. Creating Readonly Properties
A mapped type can add the readonly modifier to every property.
This prevents normal property reassignment through TypeScript type checking.
Example
interface Employee {
id: number;
name: string;
department: string;
}
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
type ReadonlyEmployee = MyReadonly<Employee>;
const employee1: ReadonlyEmployee = {
id: 101,
name: "Priya",
department: "IT"
};
console.log(employee1.name);
console.log(employee1.department);
// This would cause a TypeScript error:
// employee1.department = "HR";
Expected Output
Priya
IT
The properties remain readable, but normal reassignment is disallowed. The readonly modifier does not make nested objects deeply immutable or provide runtime security.
6. Removing Modifiers with -? and -readonly
Mapped Types can remove existing property modifiers.
The -? modifier removes optionality, while
-readonly removes readonly.
Example
interface Settings {
readonly theme?: string;
readonly language?: string;
}
type MutableRequired<T> = {
-readonly [K in keyof T]-?: T[K];
};
type UpdatedSettings = MutableRequired<Settings>;
const settings: UpdatedSettings = {
theme: "Dark",
language: "English"
};
settings.theme = "Light";
console.log(settings.theme);
console.log(settings.language);
Expected Output
Light
English
UpdatedSettings requires both properties and permits reassignment through normal TypeScript code because the optional and readonly modifiers have been removed.
7. Key Remapping with as
Mapped Types support the as clause, which lets you
change property names while mapping over existing keys.
Template literal types and utility types can be used to build
the new keys.
Example: Create Getter Methods
interface Person {
name: string;
age: number;
}
type GetterMethods<T> = {
[K in keyof T as K extends string
? `get${Capitalize<K>}`
: never]: () => T[K];
};
const personGetters: GetterMethods<Person> = {
getName: () => "Rahul",
getAge: () => 22
};
console.log(personGetters.getName());
console.log(personGetters.getAge());
Expected Output
Rahul
22
Key Remapping Workflow
Original Keys
Start with name and age.
Transform Keys
Use as and Capitalize to create new property names.
Getter Methods
Generate getName and getAge function properties.
8. Filtering Properties with Mapped Types
A mapped type can use as and never to omit
selected keys. A key mapped to never does not appear in the resulting type.
Example: Remove a Property
interface User {
id: number;
name: string;
password: string;
}
type PublicUser = {
[K in keyof User as Exclude<K, "password">]: User[K];
};
const user1: PublicUser = {
id: 1,
name: "Priya"
};
console.log(user1.id);
console.log(user1.name);
Expected Output
1
Priya
The mapped type excludes the password property from the resulting type. This is a type transformation, not a runtime mechanism for removing passwords from objects or securing sensitive information.
9. Transforming Property Types
A mapped type can transform the type of each property instead of keeping its original type. For example, every property can be represented as a string.
Example
interface Product {
id: number;
name: string;
price: number;
}
type StringValues<T> = {
[K in keyof T]: string;
};
type ProductForm = StringValues<Product>;
const productForm: ProductForm = {
id: "101",
name: "Keyboard",
price: "1200"
};
console.log(productForm.id);
console.log(productForm.name);
console.log(productForm.price);
Expected Output
101
Keyboard
1200
ProductForm keeps the original property names but maps each property's type to string. This can be useful when representing values inside a form, where numeric values may initially be entered as text.
10. Practical Example: Update Employee Data
In an application, the original employee model may contain required properties. A mapped type can create an update type where only the provided properties are accepted.
Example
interface Employee {
id: number;
name: string;
department: string;
salary: number;
}
type EmployeeUpdate = {
[K in keyof Employee]?: Employee[K];
};
const employeeUpdate: EmployeeUpdate = {
department: "Development",
salary: 45000
};
console.log(employeeUpdate.department);
console.log(employeeUpdate.salary);
Expected Output
Development
45000
Practical Workflow Diagram
Employee Type
Defines the required properties.
EmployeeUpdate
Maps every property and makes it optional.
Update Data
Supplies only the properties that need updating.
11. Mapped Types vs Utility Types
Mapped Types are a type-building technique. Many built-in Utility Types use mapped type syntax to produce common transformations.
| Feature | Mapped Types | Utility Types |
|---|---|---|
| Purpose | Build custom types by mapping over keys. | Provide reusable type transformations. |
| Syntax | [K in keyof T] |
Partial<T>, Readonly<T> |
| Custom transformations | Can define specialized rules for properties. | Use predefined transformations or combine utilities. |
| Common use | Generate optional fields, remap keys or transform values. | Reuse standard patterns such as Partial and Pick. |
12. Important Rules of Mapped Types
| Syntax | Purpose |
|---|---|
keyof T |
Gets the keys of type T. |
[K in keyof T] |
Maps over the keys of T. |
T[K] |
Gets the property type corresponding to K. |
?: |
Adds optionality to a property. |
readonly |
Adds the readonly modifier. |
-? |
Removes optionality. |
-readonly |
Removes the readonly modifier. |
as |
Remaps property keys. |
never in key remapping |
Omits the corresponding key from the result. |
Summary
Mapped Types create new types by iterating over existing properties.
The keyof operator gets property keys, and
T[K] accesses the type of each property.
Mapped Types can add or remove optional and readonly modifiers,
transform property types, remap keys using as and
exclude keys using never.
You have completed the Advanced Types module. Next, start Modules and Async to learn TypeScript modules, namespaces, promises, async/await, error handling and imports/exports.