Codectionary / Developer documentation / TypeScript

Adding and Removing Mapped-Type Modifiers

Mapped types can add or remove readonly and optional modifiers from properties.

What it is and why to use it

Mapped types can add or remove readonly and optional modifiers from properties. The minus prefix removes a modifier, while a plain modifier or plus prefix adds it. This is useful for describing a completed editable form derived from a read-only or partial model.

Common mistakes and limitations

Removing optionality does not populate missing runtime fields. Removing readonly changes only type checking, not frozen object descriptors. Prefer the built-in Required or Readonly utilities when they express the entire transformation clearly.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

type Editable<T> = { -readonly [K in keyof T]-?: T[K] };

Examples

Adding and Removing Mapped-Type Modifiers

Standalone TypeScript 5.8+ example; expected output is explained below.

type Draft = { readonly name?: string };
type Editable<T> = { -readonly [K in keyof T]-?: T[K] };
const profile: Editable<Draft> = { name: "John" };
profile.name = "James";
console.log(profile.name);
  1. The mapped type visits name and removes its readonly and optional modifiers.
  2. The object must now provide a name and the resulting type permits assignment.
  3. Changing the field prints James. This describes the new object’s allowed operations without modifying the original Draft type.
  4. Expected output: James

Best practices

  • Removing optionality does not populate missing runtime fields. Removing readonly changes only type checking, not frozen object descriptors. Prefer the built-in Required or Readonly utilities when they express the entire transformation clearly.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading