📘
Mapped Types: Transforming Types
Advanced
130 XP
50 min
Lesson Content
Mapped Types
Mapped types allow you to create new types by transforming properties of existing types.
Basic Mapped Type
type Readonly = {
readonly [P in keyof T]: T[P];
};
type ReadonlyUser = Readonly; Modifiers
// Remove readonly
type Writable = {
-readonly [P in keyof T]: T[P];
};
// Remove optional
type Required = {
[P in keyof T]-?: T[P];
}; Key Remapping
type Getters = {
[K in keyof T as `get${Capitalize}`]: () => T[K];
}; Example Code
Understanding mapped type transformations
// Mapped types work at compile time
// For practice, simulate property transformation
interface User {
name: string;
age: number;
}
// Simulate making all properties optional
function makeOptional(obj: User): Partial<User> {
return obj;
}
const user: Partial<User> = makeOptional({ name: "John", age: 30 });
console.log(user);Expected Output:
{ name: 'John', age: 30 }Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code