SifMcarby
Published on

Partial type in TypeScript

Authors
  • avatar
    Name
    Sif Mcarby
    Twitter

What is Partial<T> in TypeScript?

Partial<T> is a special TypeScript feature that makes all properties of a type optional. It’s helpful when you don’t want to provide all the details of an object.

How Does Partial<T> Work?

It works like this:

type Partial<T> = {
  [P in keyof T]?: T[P];
};

This means each property in the type becomes optional.

Example: Basic Usage

interface User {
  id: number;
  name: string;
  email: string;
}

const updateUser = (id: number, userUpdates: Partial<User>) => {
  console.log(`Updating user ${id} with:`, userUpdates);
};

updateUser(1, { name: 'Alice' });
updateUser(2, { email: 'bob@example.com' });

In this example, you can update only the name or email without needing to include id.

Real-Life Example: Updating Products

Imagine updating product details in a database:

interface Product {
  id: string;
  name: string;
  price: number;
  description?: string;
}

function updateProduct(id: string, productUpdates: Partial<Product>) {
  const db = new Map<string, Product>();
  const existingProduct = db.get(id);

  if (!existingProduct) {
    throw new Error('Product not found');
  }

  const updatedProduct = { ...existingProduct, ...productUpdates };
  db.set(id, updatedProduct);
  console.log(`Product ${id} updated:`, updatedProduct);
}

updateProduct('123', { price: 29.99 });
updateProduct('456', { name: 'New Name' });

Here, you can update just the price or name without touching other properties.

Why Use Partial<T>?

  1. Simplicity: Update only what you need.
  2. Cleaner Code: Avoid sending unnecessary data.
  3. Reusability: Works with any object type.

Example: Form Inputs

For forms, not all fields might be filled:

interface Profile {
  username: string;
  bio?: string;
  avatarUrl?: string;
}

function saveProfile(profileUpdates: Partial<Profile>) {
  console.log('Saving profile updates:', profileUpdates);
}

saveProfile({ bio: 'Loves TypeScript' });
saveProfile({ avatarUrl: 'https://example.com/avatar.png' });

This way, you can save only the fields a user updates.


Partial<T> is a simple and useful tool for making objects flexible and easier to work with. Use it when you don’t need all properties at once.