Code Logo

Optional Fields with Partial<T>

Published at25 Jul 2026
TypeScript Generics & Advanced Types Medium 0 views
Like0

Write a TypeScript function that takes an object and a Partial object representing partial updates, merges them, and returns the updated object. Partial is a utility type that makes all properties of T optional (T | undefined).

Partial is one of TypeScript's most useful built-in utility types. It takes a type T and returns a new type where every property of T is marked as optional with ?. This is implemented as a mapped type: { [P in keyof T]?: T[P] }. Partial is especially useful for update functions where only some fields need to be provided.

TypeScript provides several utility types beyond Partial: Required (all required), Readonly (all readonly), Pick (select keys), Omit (exclude keys), Record (key-value type), and more. Understanding these utilities is essential for writing concise, type-safe TypeScript code.

Time complexity is O(n) where n is the number of properties in the object. Space complexity is O(n) for the merged object. The type-level Partial adds no runtime cost.

Edge cases include empty Partial (return original object), all fields updated, and ensuring the spread operator creates a shallow copy.

Example Input & Output

Example 1
Input
{"name":"Alice","age":30,"email":"a@x.com"},{"age":31}
Output
{"name":"Alice","age":31,"email":"a@x.com"}
Explanation

Update age only

Example 2
Input
{"name":"A","age":1,"email":"a"},{"name":"B","age":2,"email":"b"}
Output
{"name":"B","age":2,"email":"b"}
Explanation

All fields updated

Example 3
Input
{"name":"Eve","age":35,"email":"e@x.com"},{}
Output
{"name":"Eve","age":35,"email":"e@x.com"}
Explanation

No changes

Example 4
Input
{"name":"Bob","age":25,"email":"b@x.com"},{"name":"Robert"}
Output
{"name":"Robert","age":25,"email":"b@x.com"}
Explanation

Update name only

Example 5
Input
{"name":"X","age":10,"email":"x"},{"email":"y"}
Output
{"name":"X","age":10,"email":"y"}
Explanation

Update email only

Algorithm Flow

Recommendation Algorithm Flow for Optional Fields with Partial<T>
Recommendation Algorithm Flow for Optional Fields with Partial<T>

Solution Approach

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

function solution(user: User, updates: Partial<User>): User {
  return { ...user, ...updates };
}

Best Answers

typescript - Approach 1
interface User {
  name: string;
  age: number;
  email: string;
}

function solution(user: User, updates: Partial<User>): User {
  return { ...user, ...updates };
}