Tutorials / TypeScript: Beginner to Advanced / Built-in utility types: Partial, Pick, Omit, Record and more

Built-in utility types: Partial, Pick, Omit, Record and more

16 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

Reusing types without copying them

Imagine a User interface with ten fields. Now you need a type for the "update user" form, where every field is optional. And another type for a public profile without the password hash. Writing each of them out by hand duplicates information, and the copies drift apart.

TypeScript ships with utility types that create new types from existing ones. They are generic types, and they are available everywhere with no import.

We will use this interface through the lesson:

interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  role: "admin" | "member";
}

Partial and Required

Partial<T> makes every property optional. Required<T> does the opposite.

interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  role: "admin" | "member";
}

function updateUser(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}

const sara: User = { id: 1, name: "Sara", email: "s@example.com", passwordHash: "x", role: "member" };
const updated = updateUser(sara, { name: "Sara Khan" });
console.log(updated.name, updated.role);   // Sara Khan member

Partial is the classic choice for update functions and for options objects where everything has a default.

Pick and Omit

Pick<T, Keys> builds a type with only the chosen properties. Omit<T, Keys> builds one with everything except the chosen ones.

interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  role: "admin" | "member";
}

type PublicUser = Omit<User, "passwordHash">;
type UserSummary = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;

const summary: UserSummary = { id: 1, name: "Ali" };

function toPublic(user: User): PublicUser {
  const { passwordHash, ...rest } = user;
  return rest;
}

console.log(summary.name, toPublic({ id: 2, name: "Z", email: "z@example.com", passwordHash: "h", role: "admin" }));

The keys you pass must exist on the type. If you rename a property in User, every Pick and Omit that mentions the old name shows an error. That is much better than a copy that quietly stops matching.

Readonly

interface Settings {
  theme: string;
  fontSize: number;
}

const defaults: Readonly<Settings> = { theme: "light", fontSize: 14 };
// defaults.theme = "dark";   // Error: read-only
console.log(defaults.theme);

const list: readonly number[] = [1, 2, 3];
// list.push(4);              // Error
console.log(list.length);

Readonly<T> is shallow. Nested objects can still be changed. It only protects at compile time.

Record

Record<Keys, Value> builds an object type with the given keys, all of the same value type. It is the neat way to write a dictionary or a lookup table.

type Role = "admin" | "editor" | "viewer";

const permissions: Record<Role, string[]> = {
  admin: ["read", "write", "delete"],
  editor: ["read", "write"],
  viewer: ["read"],
};

console.log(permissions.editor.join(", "));
// If you forget a role, the compiler reports that it is missing.

const wordCount: Record<string, number> = {};
for (const word of ["a", "b", "a"]) {
  wordCount[word] = (wordCount[word] ?? 0) + 1;
}
console.log(wordCount);

When the keys are a union, Record forces you to provide every one. That is useful for things like a label for each status: adding a new status later makes the compiler show every place that must be updated.

Extract, Exclude and NonNullable

These work on unions:

type Event = "click" | "hover" | "keydown" | "keyup";

type KeyEvent = Extract<Event, "keydown" | "keyup">;   // "keydown" | "keyup"
type MouseEvent2 = Exclude<Event, KeyEvent>;            // "click" | "hover"

type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>;                     // string

const e: KeyEvent = "keyup";
const m: MouseEvent2 = "click";
const n: Name = "Ali";
console.log(e, m, n);

ReturnType, Parameters and Awaited

These read information from function types:

function createUser(name: string, age: number) {
  return { id: Date.now(), name, age, createdAt: new Date() };
}

type NewUser = ReturnType<typeof createUser>;
type CreateArgs = Parameters<typeof createUser>;   // [name: string, age: number]

const args: CreateArgs = ["Sara", 28];
const user: NewUser = createUser(...args);
console.log(user.name);

async function loadCount(): Promise<number> {
  return 5;
}

type Count = Awaited<ReturnType<typeof loadCount>>;   // number
const count: Count = 10;
console.log(count);

typeof createUser takes the type of an existing function value. ReturnType then extracts what it returns, so you do not need to write an interface by hand, and the type always follows the code. Awaited unwraps a promise type, which is what you need for the result of an async function.

Combining them

Utility types compose:

interface Article {
  id: number;
  title: string;
  body: string;
  published: boolean;
}

// For editing: id is required and cannot change, everything else is optional
type ArticleUpdate = Pick<Article, "id"> & Partial<Omit<Article, "id">>;

const change: ArticleUpdate = { id: 3, title: "New title" };
console.log(change.id, change.title);

Read these from the inside out: Omit removes id, Partial makes the rest optional, Pick keeps only id, and & joins the two.

Quick reference

UtilityResult
Partial<T>All properties optional
Required<T>All properties required
Readonly<T>All properties read-only
Pick<T, K>Only the keys K
Omit<T, K>Everything but the keys K
Record<K, V>Object with keys K and values V
Extract<U, M> / Exclude<U, M>Keep or remove members of a union
NonNullable<T>Remove null and undefined
ReturnType<F> / Parameters<F>Function return and parameter types
Awaited<P>The value a promise resolves to

Common mistakes

  • Rewriting a type by hand when a utility would do. The copy will drift.
  • **Expecting Readonly to be deep.** Nested objects stay mutable.
  • **Using Partial for data that is not actually optional.** A function that takes Partial<User> also accepts {}.
  • **Using Omit with a misspelt key.** Omit does not check that the key exists, unlike Pick. A typo silently omits nothing.
  • **Reaching for Record<string, any>.** Give the value a real type.

Try it yourself

  1. From an interface Product with five fields, build ProductPreview using Pick, and NewProduct using Omit.
  2. Create a Record<"draft" | "published" | "archived", string> with a label for each state.
  3. Use ReturnType to get the type of Date.now and of JSON.parse. What do you get?
  4. Write a function merge<T>(base: T, changes: Partial<T>): T.
typescript
interface User {
  id: number;
  name: string;
  email: string;
  passwordHash: string;
  role: "admin" | "member";
}

function updateUser(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}

const sara: User = { id: 1, name: "Sara", email: "s@example.com", passwordHash: "x", role: "member" };
const updated = updateUser(sara, { name: "Sara Khan" });
console.log(updated.name, updated.role);   // Sara Khan member

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account