Lesson 10 of 11 · 11 min

Utility types

TypeScript ships utility types that build new types from existing ones, so you do not repeat yourself:

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}
Utility Gives
Partial<User> every property optional (good for "changes")
Required<T> every property required
Readonly<User> every property read-only
Pick<User, "id" | "name"> only those properties
Omit<User, "password"> everything except those
Record<"admin" | "guest", boolean> an object with exactly those keys
type UserSummary = Pick<User, "id" | "name">;      // { id: number; name: string }
type Settings = Record<"darkMode" | "emails", boolean>;

Because these are derived, adding a field to User updates every type built from it automatically.

Types are not runtime checks

Omit<User, "password"> only changes what TypeScript allows you to write. The object still contains whatever you put in it. To really remove the password, the code must leave it out, for example with destructuring:

const { password, ...safe } = user;   // safe has everything except password

Your task

  1. updateUser(user: User, changes: Partial<User>): User returns a new user with the changes applied.
  2. Define type PublicUser = Omit<User, "password">.
  3. toPublic(user: User): PublicUser returns a copy without the password.
main.ts
interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

function updateUser(user: User, changes: User): User {
  return user;
}

const ana: User = { id: 1, name: "Ana", email: "a@x.com", password: "secret" };
console.log(updateUser(ana, { name: "Anna" }));

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…