Syncing account progress…

Back

Intermediate · 14 min

Practical utility types

Use Pick, Omit, Partial, and Record to describe everyday data shapes.

Select fields for a view

Pick keeps selected properties; Omit removes named properties from a type. Neither operation removes runtime data. To build a public object without a private field, construct a new object containing only the fields you intend to expose.

type Member = { name: string; email: string; points: number };
type Summary = Pick<Member, "name" | "points">;
const member: Member = { name: "Ada", email: "private@example.test", points: 4 };
const summary: Summary = { name: member.name, points: member.points };
console.log(Object.keys(summary).join(","));

Output

name,points

Describe updates and fixed keys

Partial makes properties optional and is shallow: it does not recursively change nested objects. Record maps a set of keys to a value type. A finite key union requires every listed key. Use these types to describe a deliberate update or lookup structure.

type Preferences = { minutes: number; topic: string };
const patch: Partial<Preferences> = { minutes: 20 };
const labels: Record<"short" | "long", string> = { short: "Quick", long: "Extended" };
console.log(String(patch.minutes) + ": " + labels.short);

Output

20: Quick

Put it into practice

  1. Read the types and predict the output before running the examples.
  2. Fix the task without using "any" or a type assertion, then check both practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Complete a typed lookup

Add the missing "done" key with the value 3 to "counts". Keep the finite Record type and display the sum.

Show solution
type Status = "todo" | "done";
const counts: Record<Status, number> = { todo: 2, done: 3 };
const total = counts.todo + counts.done;
console.log(total);

Supplying both keys satisfies the lookup contract. Each indexed property is numeric, so the sum is five.

Practice