What are utility types in typescript?

TypeScript provides several built-in utility types that help you transform and compose types without rewriting them from scratch. These utilities make your code more expressive, reusable, and easier to maintain.

They are especially helpful when working with large object types, API responses, or manipulating types based on different needs.

Common utility types and how to use them

1. Partial

Makes all properties of a type optional.

type User = {
  id: number;
  name: string;
};

const updateUser = (user: Partial<User>) => {
  // You can now pass only some fields
};


2. Required

Makes all properties of a type required.

type Props = {
  id?: string;
  value?: number;
};

const input: Required<Props> = {
  id: "abc",
  value: 42,
};


3. Readonly

Marks all properties as read-only (immutable).

type Settings = {
  theme: string;
};

const config: Readonly<Settings> = {
  theme: "dark",
};

// config.theme = "light"; // ❌ Error


4. Pick

Creates a new type by picking specific properties.

type Post = {
  id: number;
  title: string;
  content: string;
};

type PostPreview = Pick<Post, "id" | "title">;

5. Omit

Creates a new type by omitting specific properties.

type User = {
  id: number;
  name: string;
  password: string;
};

type PublicUser = Omit<User, "password">;


6. Record

Constructs a type with a set of keys K and values of type T.

type Theme = "dark" | "light";

const themeColors: Record<Theme, string> = {
  dark: "#000000",
  light: "#ffffff",
};


7. Exclude

Removes types from T that are assignable to U.

type Roles = "admin" | "user" | "guest";

type NonGuests = Exclude<Roles, "guest">; // "admin" | "user"


8. Extract

Opposite of Exclude: keeps only types assignable to U.

type Status = "success" | "error" | "loading";

type LoadingOnly = Extract<Status, "loading">; // "loading"

9. Nonnullable

Removes null and undefined from a type.

type MaybeString = string | null | undefined;

type StrictString = NonNullable<MaybeString>; // string


When should you use utility types?

UtilityUse Case Example
PartialFor update forms or patch operations
PickFor selecting a subset of fields from large objects
OmitWhen exposing data without sensitive information
RecordFor key-value maps with predefined keys
RequiredWhen you want to enforce presence of all fields
ReadonlyFor immutable configurations or props

Conclusion

TypeScript’s utility types are essential tools for transforming types in a declarative and flexible way. They can help you avoid duplication, simplify your logic, and create safer, more predictable code. Mastering these utilities is a key step in becoming a productive TypeScript developer.