Partial object updates
An update or patch API accepts only the fields that need changing while retaining the original object model.
TypeScript · Type Alias
Partial<Type> constructs a type with every property of Type made optional. It represents any subset of the original type and is commonly used for partial updates.
Partial<T> creates a type whose properties correspond to T, but each property is optional. It is useful when an operation accepts a subset of an existing object’s fields, such as a patch or update function, while preserving each field’s original value type.
Partial<Type>| Name | Type | Description |
|---|---|---|
Type | type | The source object type whose properties become optional. |
A type with all properties of Type set to optional.
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>): Todo {
return { ...todo, ...fieldsToUpdate };
}
const todo = { title: "organize desk", description: "clear clutter" };
const updated = updateTodo(todo, { description: "throw out trash" });
console.log(updated);The update argument can contain any subset of Todo properties, while the returned object remains a complete Todo.
An update or patch API accepts only the fields that need changing while retaining the original object model.
A builder or configuration layer collects fields incrementally before producing a complete value.
A generic helper needs to describe a subset of an existing object shape without duplicating its property declarations.
Partial<T> is a global utility type that makes every property in T optional. The resulting type represents all subsets of T while retaining each property’s original type.
Follow-up: How can its transformation be expressed? A mapped type equivalent is { [P in keyof T]?: T[P] }.
Use Partial<T> for APIs that update only selected fields of an existing object. For example, an update function can accept Partial<Todo> while merging those fields into a complete Todo.
Follow-up: How would you require at least one update field? Define a separate mapped or union type that makes one key required; Partial<T> alone also allows {}.
Partial<T> was released in TypeScript 2.1 and is included globally in the standard library. It is one of TypeScript’s built-in utility types.
Follow-up: What related transformation makes properties immutable instead? Readonly<T> preserves the property set while preventing assignment through the resulting type.
ReadonlyPickRecordMapped types