Partial, Required and Readonly

Changing All Properties at Once

UtilityResult
Partial<T>every property optional
Required<T>every property required (removes ?)
Readonly<T>every property readonly

Example

Partial is perfect for update functions (PATCH requests) where the caller sends only the fields that changed.

type Product = { id: number; name: string; price: number; stock: number };

function updateProduct(p: Product, changes: Partial<Omit<Product, "id">>): Product {
  return { ...p, ...changes };
}

const kettle: Product = { id: 1, name: "Kettle", price: 1299, stock: 10 };
console.log(updateProduct(kettle, { price: 1199 }));
console.log(updateProduct(kettle, { stock: 0, name: "Electric Kettle" }));

type Settings = { theme?: "light" | "dark"; lang?: string };
const defaults: Required<Settings> = { theme: "light", lang: "en" };
console.log({ ...defaults, ...{ lang: "hi" } });

Output

{ id: 1, name: 'Kettle', price: 1199, stock: 10 }
{ id: 1, name: 'Electric Kettle', price: 1299, stock: 0 }
{ theme: 'light', lang: 'hi' }

Readonly in Action

Example

A Readonly<Product> cannot be modified (TS2540). Use it for state that must be updated immutably, like Redux or React state.

type Product = { id: number; price: number };
const frozen: Readonly<Product> = { id: 1, price: 1299 };
frozen.price = 999;

Compiler output (tsc)

Line 3: error TS2540: Cannot assign to 'price' because it is a read-only property.