Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

TypeScript Utility Types: Partial, Pick, Omit, Record and Beyond

Utility types derive contracts from existing models instead of duplicating definitions. Frontend applications use them for profile updates, component settings, status maps and API responses. They do not transform runtime objects. This guide separates compiler guarantees from operations JavaScript must actually perform.

Published Written by Reading time 8 min read
On this page Contents: quick navigation between sections

Partial: restrict the fields that can be updated

interface Profile {
  id: string;
  displayName: string;
  bio: string | null;
  role: "member" | "admin";
}

type ProfilePatch = Partial<Pick<Profile, "displayName" | "bio">>;

function updateProfile(profile: Profile, patch: ProfilePatch): Profile {
  const updatedProfile = { ...profile };

  if (patch.displayName !== undefined) {
    updatedProfile.displayName = patch.displayName;
  }

  if (patch.bio !== undefined) {
    updatedProfile.bio = patch.bio;
  }

  return updatedProfile;
}

const profile: Profile = {
  id: "u1",
  displayName: "Ada",
  bio: "Engineer",
  role: "member",
};

const updated = updateProfile(profile, { bio: null });

console.log(updated.bio); // null
console.log(profile.bio); // Engineer

Partial<T> makes top-level properties optional. For a profile update, exposing every field is too broad: Partial<Pick<Profile, ...>> limits the contract to display name and biography, and the function deliberately copies only those values. [1][7]

Here an omitted field means no change, while null clears the biography. With exactOptionalPropertyTypes, explicit undefined is rejected unless the property type permits it. Reading an optional property can still produce undefined. Server-side request validation and authorization are still required. [2][8]

Required: normalize incomplete configuration

interface Preferences {
  theme?: "light" | "dark";
  compact?: boolean;
}

function resolvePreferences(input: Preferences): Required<Preferences> {
  return {
    theme: input.theme ?? "light",
    compact: input.compact ?? false,
  };
}

const preferences = resolvePreferences({ compact: false });

console.log(preferences); // { theme: "light", compact: false }

Required<T> removes top-level optional modifiers but does not supply missing values. The normalization function must apply its own defaults. [1][7]

The ?? operator preserves a valid false, unlike ||, which treats it as falsy. Required is not equivalent to NonNullable: an explicitly allowed null remains part of the type.

Pick and Omit: API contracts and privacy

interface Account {
  id: string;
  displayName: string;
  email: string;
  passwordHash: string;
}

type PublicAccount = Pick<Account, "id" | "displayName">;
type AccountWithoutHash = Omit<Account, "passwordHash">;

function toPublicAccount(account: Account): PublicAccount {
  return {
    id: account.id,
    displayName: account.displayName,
  };
}

const account: Account = {
  id: "u1",
  displayName: "Ada",
  email: "ada@example.com",
  passwordHash: "example-hash",
};

const publicAccount = toPublicAccount(account);

console.log(Object.keys(publicAccount)); // ["id", "displayName"]

Pick<T, K> derives a type containing selected properties; Omit<T, K> leaves specified properties out of the type. Prefer an allowlist for public responses so adding a private field to the source model does not automatically expand the public contract. [1]

Assigning an Account to a PublicAccount variable does not strip the hash or email from the object. Structural assignability accepts compatible values, and types are erased during compilation. toPublicAccount constructs a new object; the server still needs authorization checks. [3][8]

Record: exhaustive maps and dynamic keys

type RequestStatus = "idle" | "loading" | "success" | "error";

const statusLabels = {
  idle: "Ready",
  loading: "Loading",
  success: "Done",
  error: "Failed",
} satisfies Record<RequestStatus, string>;

function getStatusLabel(status: RequestStatus): string {
  return statusLabels[status];
}

const durations: Record<string, number> = { home: 120 };

function getDuration(route: string): number | undefined {
  return Object.hasOwn(durations, route) ? durations[route] : undefined;
}

console.log(getStatusLabel("success")); // Done
console.log(getDuration("missing")); // undefined

Record<RequestStatus, string> requires a label for each status. satisfies checks the object literal without replacing its inferred type with the Record annotation. Adding a new status to the union exposes a missing label at compile time. [1][5]

Record<string, number> does not mean every possible key exists at runtime. Enable noUncheckedIndexedAccess so an unchecked lookup includes undefined. Object.hasOwn distinguishes own properties from inherited ones; Map is also an option for arbitrary keys. [4]

Readonly: immutability versus actual copies

interface Cart {
  items: string[];
  currency: string;
}

type CartSnapshot = Readonly<{
  items: readonly string[];
  currency: string;
}>;

function createSnapshot(cart: Cart): CartSnapshot {
  return Object.freeze({
    items: Object.freeze([...cart.items]),
    currency: cart.currency,
  });
}

const cart: Cart = { items: ["book"], currency: "EUR" };
const snapshot = createSnapshot(cart);

cart.items.push("pen");

console.log(snapshot.items); // ["book"]
console.log(Object.isFrozen(snapshot.items)); // true

Readonly<T> prevents top-level property assignments during type checking. It does not automatically protect nested objects or arrays from mutation through other references. [1][3]

The cart snapshot uses a read-only array type, a copied list and two Object.freeze calls. Adding an item to the original cart therefore does not change the snapshot. Freezing is shallow; object-valued items would need their own copying and freezing strategy.

Extract, Exclude and NonNullable: model application states

type DownloadState =
  | { kind: "idle" }
  | { kind: "success"; url: string }
  | { kind: "error"; message: string };

type SuccessState = Extract<DownloadState, { kind: "success" }>;
type PendingOrFailed = Exclude<DownloadState, SuccessState>;

function getDownloadUrl(state: DownloadState): string | undefined {
  if (state.kind !== "success") {
    return undefined;
  }

  return state.url;
}

type DownloadUrl = NonNullable<ReturnType<typeof getDownloadUrl>>;

const url: DownloadUrl = "https://example.com/report.pdf";

console.log(getDownloadUrl({ kind: "success", url }));
console.log(getDownloadUrl({ kind: "idle" })); // undefined

Extract retains union members assignable to a target type, Exclude removes them and NonNullable excludes null and undefined. A download state model can derive the success variant and remaining states without repeating their shapes. [1][6]

The function checks kind before reading url. NonNullable<ReturnType<...>> describes an existing download URL, but does not guarantee that every call returns one. Check the actual value to establish that guarantee. [9]

Parameters, ReturnType and Awaited: derive types from functions

async function loadCatalog(category: string, limit: number) {
  const products = [{ id: "p1", category, price: 1200 }];

  return products.slice(0, limit);
}

type CatalogArguments = Parameters<typeof loadCatalog>;
type Catalog = Awaited<ReturnType<typeof loadCatalog>>;
type CatalogItem = Catalog[number];

async function getCatalogTotal(...args: CatalogArguments): Promise<number> {
  const products: Catalog = await loadCatalog(...args);

  return products.reduce((total, product) => total + product.price, 0);
}

void getCatalogTotal("books", 10).then(console.log); // 1200

Parameters derives an argument tuple, ReturnType captures a return type and Awaited models unwrapping a promise result. This keeps the catalog total function aligned with the data-loading signature. [1]

The example uses local data and prices in minor currency units. For a real API, derive the result from a validated contract rather than unchecked JSON. For overloaded functions, Parameters and ReturnType use the last overload signature. [1][8]

Omit on unions: when distribution matters

type Payment =
  | { kind: "card"; id: string; lastFour: string }
  | { kind: "bank"; id: string; bankName: string };

type DistributiveOmit<Model, Keys extends PropertyKey> = Model extends unknown
  ? Omit<Model, Keys>
  : never;

type PaymentPreview = DistributiveOmit<Payment, "id">;

function describePayment(payment: PaymentPreview): string {
  if (payment.kind === "card") {
    return `Card: ${payment.lastFour}`;
  }

  return `Bank: ${payment.bankName}`;
}

console.log(describePayment({ kind: "card", lastFour: "1234" }));
console.log(describePayment({ kind: "bank", bankName: "Example Bank" }));

The built-in Omit<Payment, "id"> can lose properties unique to individual variants because it works from the keys available on the entire union. Card and bank payments have different data that must remain correlated with kind. [6][7]

A conditional type with a naked Model type parameter distributes the operation over each variant. DistributiveOmit removes the identifier while preserving lastFour and bankName in their respective branches. Avoid custom helpers when a built-in type or an explicit contract expresses the design more clearly.

Use utility types for contracts that genuinely share a source of change. Pick restricts public views, Partial describes updates, Record ensures exhaustive maps and Readonly documents mutation constraints. Type transformations do not replace data mapping, validation or authorization. When business contracts evolve independently, an explicit separate type can be clearer than a stack of utility types.

TypeScript Utility Types Partial Pick Omit Record Required Readonly Extract Exclude NonNullable ReturnType Parameters Awaited Mapped Types

Frequently asked questions

Is Partial recursive?

No. It makes top-level properties optional; nested objects retain their existing types. [1][7]

Does Omit remove properties from JSON?

No. Map or filter the actual object before serialization. [8]

Does Record require every key?

Yes for a finite union of required keys; Record<string, T> cannot guarantee arbitrary keys exist at runtime. [1][4]

Does Readonly replace Object.freeze?

No. One constrains type checking, the other changes JavaScript object behavior and is shallow. [3][8]

How do I derive an async function result type?

Use Awaited<ReturnType<typeof fn>> to derive the resolved value type. [1]

Sources and references

  1. TypeScript Handbook, Utility Types↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11
  2. TypeScript TSConfig, exactOptionalPropertyTypes↩
  3. TypeScript Handbook, Object Types↩1↩2↩3
  4. TypeScript TSConfig, noUncheckedIndexedAccess↩1↩2
  5. TypeScript 4.9, satisfies↩
  6. TypeScript Handbook, Conditional Types↩1↩2
  7. TypeScript Handbook, Mapped Types↩1↩2↩3↩4
  8. TypeScript Handbook, The Basics↩1↩2↩3↩4↩5
  9. TypeScript Handbook, Narrowing↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning