Lesson 18 +10 XP

Object Utility Types (Partial, Required, Readonly, Record)

Object Utility Types

TypeScript provides built-in global utility types to manipulate existing object types.

Standard Object Utilities Overview

Utility TypeDescription
Partial<T>Makes all properties of T optional (?).
Required<T>Makes all properties of T mandatory (removes ?).
Readonly<T>Makes all properties of T read-only (readonly).
Record<K, T>Constructs an object type with property keys K and values of type T.

Code Examples

interface User {
  id: number;
  name: string;
  email?: string;
}

// 1. Partial: useful for updates
function updateUser(id: number, fieldsToUpdate: Partial<User>) {
  // fieldsToUpdate allows optional id, name, email
}

// 2. Readonly: prevents modifications
const frozenUser: Readonly<User> = { id: 1, name: "Alice" };
// frozenUser.name = "Bob"; // Error!

// 3. Record: key-value dictionary mapping
type Page = "home" | "about" | "contact";
type PageInfo = { title: string };

const nav: Record<Page, PageInfo> = {
  home: { title: "Home" },
  about: { title: "About Us" },
  contact: { title: "Contact Us" }
};

TL;DR

  • Partial<T> turns all fields optional; Required<T> turns all fields required.
  • Readonly<T> prevents modifying property values.
  • Record<Keys, Type> defines structured dictionaries easily.