Back to roadmaps typescript Course

Built-in Utility Types

TypeScript provides several global utility types to facilitate common type transformations. These utilities act as built-in helpers to reshape your existing object interfaces.


1. Partial and Required

Partial

Partial<T> constructs a type with all properties of T set to optional. This is useful for update or configuration inputs.

interface Task {
  title: string;
  description: string;
  completed: boolean;
}

// All fields are optional
type TaskUpdate = Partial<Task>;

const update: TaskUpdate = {
  completed: true
};

Required

Required<T> does the opposite. It constructs a type with all properties of T set to required, even if they were originally optional.

interface OptionalUser {
  id?: string;
  name?: string;
}

// All fields are mandatory
type StrictUser = Required<OptionalUser>;

2. Readonly

Readonly<T> constructs a type with all properties of T marked as read-only. Attempts to reassign properties will raise compile errors.

interface Config {
  apiKey: string;
}

const settings: Readonly<Config> = {
  apiKey: "secret-key"
};

// settings.apiKey = "new-key"; // Error: Cannot assign to 'apiKey' because it is a read-only property.

3. Record

Record<Keys, Type> constructs an object type where the property keys are Keys and the values are Type. This is highly useful for mapping property keys to another type.

type PageName = "home" | "about" | "contact";

interface PageInfo {
  title: string;
}

// Maps each page name to its page info
const navigationMap: Record<PageName, PageInfo> = {
  home: { title: "Home Page" },
  about: { title: "About Us" },
  contact: { title: "Contact Us" }
};

4. Pick and Omit

Pick

Pick<T, Keys> constructs a type by picking a specific set of properties Keys from T.

interface UserAccount {
  id: string;
  username: string;
  email: string;
  token: string;
}

// Pick only 'username' and 'email'
type PublicProfile = Pick<UserAccount, "username" | "email">;

Omit

Omit<T, Keys> constructs a type by picking all properties from T and then removing the specified keys.

// Remove 'token' from the type
type ProfileWithoutToken = Omit<UserAccount, "token">;

5. Summary

  • Use Partial and Required to toggle optional status on object attributes.
  • Use Readonly to lock down object properties from modification.
  • Use Record to map specified keys to a concrete property type.
  • Use Pick to extract select attributes, and Omit to discard unwanted keys.
Published on Last updated: