theory.ts

Advanced TypeScript Patterns

Mapped Types

Mapped types allow modifying object types dynamically by iterating over their keys.

  • Uses `keyof` to extract keys from a type.
  • Transforms each key using `[K in keyof T]` syntax.
  • Commonly used for immutability, optional properties, and deep partials.
// Defining a mapped type to make all properties readonly
type ReadonlyUser<T> = {
  readonly [K in keyof T]: T[K];
};

interface User {
  name: string;
  age: number;
}

const user: ReadonlyUser<User> = { name: "Alice", age: 30 };
user.name = "Bob"; // Error: Cannot assign to 'name' because it is read-only.