← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 10 of 20

Utility Types - Partial

Partial<T> makes all properties of an object type optional. It is commonly used for update objects and configuration overrides.

Basic Partial

Partial<T> allows an object to contain any subset of T's original properties, turning every required property into an optional one without you having to rewrite the whole type by hand.

Example: Basic Partial

typescript
interface Todo {
  title: string;
  done: boolean;
}
type PartialTodo = Partial<Todo>;
const t: PartialTodo = { title: "Buy milk" };
console.log(t);

Partial for Updates

Partial is especially useful when a function updates only selected properties of an object, since the caller shouldn't be forced to pass every single field just to change one of them.

Example: Partial for Updates

typescript
interface Todo {
  title: string;
  done: boolean;
}
function updateTodo(todo: Todo, changes: Partial<Todo>): Todo {
  return { ...todo, ...changes };
}
const updated = updateTodo({ title: "Buy milk", done: false }, { done: true });
console.log(updated);

Partial with Interfaces

Partial works with interfaces just as well as with type aliases, and it preserves each property's original type while only changing whether that property is required or optional.

Example: Partial with Interfaces

typescript
interface Settings {
  theme: string;
  fontSize: number;
}
const patch: Partial<Settings> = { fontSize: 14 };
console.log(patch);

Partial and Type Safety

Partial does not remove type checking on the properties that are supplied — any property that is present in the object must still match its original type exactly, only its presence becomes optional.

Example: Partial and Type Safety

typescript
interface Todo {
  title: string;
  done: boolean;
}
const patch: Partial<Todo> = { done: true };
console.log(typeof patch.done);

When to Use Partial

Use Partial when an operation can legitimately accept any subset of an existing object's properties, such as a generic patch or update function in an API client.

Example: When to Use Partial

typescript
interface User {
  name: string;
  email: string;
}
function patchUser(id: number, changes: Partial<User>) {
  console.log("Patching user", id, changes);
}
patchUser(1, { email: "[email protected]" });

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.