Utility Types

Utility types are built-in TypeScript helpers that transform types. They make your types more concise, flexible, and powerful, especially when working with component props, APIs, and state.

We’ll cover the key TypeScript types you’ll encounter and use regularly when writing React code.

Partial<T>

Makes all properties optional.

// Define the original full type
interface User {
  id: string;
  name: string;
  age: number;
}

// Use Partial to make all fields optional
type UpdateUser = Partial<User>;

// You can now create an object with just some fields
const updatedUserInfo: UpdateUser = {
  name: "Bob", // no need for id or age
};

// Simulate an update function where not all user data needs to change
const updateUser = (user: UpdateUser): void => {
  // This function accepts any subset of the User fields
  console.log("Updating user with:", user);
};

updateUser(updatedUserInfo); // Updating user with: { name: "Bob" }

Use Partial when you want to allow updating or creating objects without needing all fields up front.

Required<T>

Makes all properties required (the opposite of Partial<T>).

Pick<T, K>

“Give me a type with only these specific keys from the original.”

Creates a type by picking a subset of properties from another type.

Omit<T, K>

The inverse of Pick<T>. Removes specific properties from a type.

Record<K, T>

Constructs an object type where the keys K have values of type T.

Exclude<T, U>

Removes from T the types that are assignable to U.

Extract<T, U>

Keeps only types from T that are assignable to U.

NonNullable<T>

Removes null and undefined from a type.

ReturnType<T>

Gets the return type of a function.

More can be found in the official documentation.

Last updated