TypeScript
/Intermediate
Partial<T>
Definition
A built-in utility type that constructs a new type where all properties of the given Type `T` are set to optional.
Explain Like I'm New
Imagine an application form with 20 required fields. `Partial` takes a photocopy of that form, crosses out the word 'Required' next to every single field, and writes 'Optional'.
Real World Example
Updating a user profile via a PATCH request. You don't want to send the entire `User` object (with ID, email, password) just to update their username. You type the payload as `Partial<User>`.
Common Use Cases
- •API PATCH requests
- •React `setState` (merging partial state)
- •Mocking data in Unit Tests
Interactive Example
interface Todo { title: string; description: string; completed: boolean; } // We want a function to update just ONE piece of the Todo // Using Partial<Todo> means the object can have 1, 2, or all 3 properties function updateTodo(todoToUpdate: Todo, fieldsToUpdate: Partial<Todo>) { return { ...todoToUpdate, ...fieldsToUpdate }; } const todo1: Todo = { title: "Clean room", description: "Before noon", completed: false }; // We only provide 'completed', which is perfectly valid for Partial<Todo> const updatedTodo = updateTodo(todo1, { completed: true });
Interview Questions
basic
- What does `Partial` do to required properties?
intermediate
- Does `Partial` make deeply nested properties optional?