Sub topic 2
Partial: making every property optional
This chapter assumes you can read TypeScript interfaces and type aliases, and that generic syntax such as Array<T> is familiar. You do not need to know mapped types yet. This chapter touches on them briefly, and a later chapter covers them fully.
The problem Partial solves
Many functions accept only some of an object's fields. An update endpoint receives just the fields that changed. A form holds half-filled values. A settings function takes overrides for a few defaults.
Without a utility type, you would write a second interface with every field marked ?:
interface User {
id: number;
name: string;
email?: string;
}
interface UserPatch {
id?: number;
name?: string;
email?: string;
}The two types now have to be kept in sync by hand. If someone adds age: number to User and forgets UserPatch, the compiler stays silent and the patch type is wrong.
Partial<T> derives the second type from the first.
interface User {
id: number;
name: string;
email?: string;
}
type UserPatch = Partial<User>;
const patch: UserPatch = { name: "Ada" };
const nothing: UserPatch = {};Partial<User> has the same keys as User, and each one is optional. Both { name: "Ada" } and {} are valid values. Property types are unchanged, so name is still a string when present, and { name: 42 } is still an error.
How Partial is defined
Partial is not compiler magic. It is a one-line mapped type in TypeScript's standard library:
type MyPartial<T> = { [K in keyof T]?: T[K] };Read it from the inside out:
keyof Tis the union of the property names ofT.[K in keyof T]loops over those names, producing one property per name.T[K]looks up the original type of that property, so types are preserved.- The
?after the bracket marks each produced property as optional.
Three consequences follow from this definition.
- Partial is a homomorphic mapped type, meaning it maps over
keyof Tdirectly. Because of that, modifiers already on the properties are kept. Areadonlyproperty staysreadonly. - Applied to an array or tuple type, it makes the elements optional.
Partial<[number, string]>is[number?, string?]. - Partial adds optionality only. It never removes it.
Required<T>is the inverse and is covered in its own chapter.
Typing an update function
The most common use is a function that merges a patch into an existing object:
interface User {
id: number;
name: string;
email: string;
}
function applyPatch(user: User, patch: Partial<User>): User {
return { ...user, ...patch };
}
const ada: User = { id: 1, name: "Ada", email: "[email protected]" };
const renamed = applyPatch(ada, { name: "Ada Lovelace" });
console.log(renamed); // { id: 1, name: 'Ada Lovelace', email: '[email protected]' }The caller can pass any subset of fields, and the return type stays a full User. The compiler accepts the spread because the result has every User key.
One problem remains. Callers can change id, which an update should usually forbid. The fix is to compose Partial with Omit, shown in the next section.
Restricting what can be patched
Wrap the original type in Omit first, then apply Partial:
interface User {
id: number;
name: string;
email: string;
}
type UserChanges = Partial<Omit<User, "id">>;
function updateUser(user: User, changes: UserChanges): User {
return { ...user, ...changes };
}
const ada: User = { id: 1, name: "Ada", email: "[email protected]" };
updateUser(ada, { email: "[email protected]" });
// updateUser(ada, { id: 2 }); // Error: 'id' does not exist in type 'UserChanges'Order matters. Partial<Omit<User, "id">> first removes id, then makes the rest optional. The patch type has no id key at all. Passing an object literal with id is reported as an excess property.
The undefined gotcha
By default, an optional property accepts undefined as an explicit value. So { name: undefined } is a valid Partial<User>. Spreading it silently erases data:
interface User {
id: number;
name: string;
email: string;
}
function applyPatch(user: User, patch: Partial<User>): User {
return { ...user, ...patch };
}
const ada: User = { id: 1, name: "Ada", email: "[email protected]" };
const broken = applyPatch(ada, { name: undefined });
console.log(broken.name); // undefined, although the type says stringThis compiles under strict mode. TypeScript types the spread result as if name were still a string, so the type no longer matches the runtime value. Two defenses exist.
The first is a compiler option. With "exactOptionalPropertyTypes": true in tsconfig.json, an optional property can be absent but cannot be set to undefined unless its type says so. Then { name: undefined } is rejected.
The second is to strip undefined values before merging, which also protects you when the data comes from JSON or a form:
interface User {
id: number;
name: string;
email: string;
}
function applyPatchSafe(user: User, patch: Partial<User>): User {
const defined = Object.fromEntries(
Object.entries(patch).filter(([, value]) => value !== undefined),
) as Partial<User>;
return { ...user, ...defined };
}
const ada: User = { id: 1, name: "Ada", email: "[email protected]" };
console.log(applyPatchSafe(ada, { name: undefined }).name); // "Ada"Object.fromEntries needs the ES2019 library (or newer) in your tsconfig.json lib or target setting.
| Situation | Default | With `exactOptionalPropertyTypes` |
|---|---|---|
| Omit the key: `{}` | Allowed | Allowed |
| Set the key to a value: `{ name: "Ada" }` | Allowed | Allowed |
| Set the key to `undefined`: `{ name: undefined }` | Allowed | Error |
Weak types: all-optional objects are checked specially
A type whose properties are all optional is called a weak type. TypeScript applies an extra rule to it: a value must share at least one property with the type, or the assignment fails.
interface Options {
color?: string;
size?: number;
}
const input = { colour: "red" };
// const opts: Partial<Options> = input;
// Error: Type '{ colour: string; }' has no properties in common with type 'Partial<Options>'.Without this rule, any object would be assignable to an all-optional type, and a typo such as colour would pass unnoticed. The rule helps, but it applies only when the source has at least one property. The empty object {} is always accepted.
The rule also means that Partial<T> for a T with only optional fields behaves the same as T, so applying it twice changes nothing.
Partial is shallow
Partial makes only the top-level properties optional. Nested objects keep their required fields:
interface Settings {
theme: { color: string; size: number };
language: string;
}
const update: Partial<Settings> = {
theme: { color: "red" }, // Error: Property 'size' is missing
};You can omit theme entirely, but if you provide it, you must provide all of it. That matches the usual meaning of a replace operation, but not a deep merge. If you need nested optionality, you write a recursive type. A later chapter builds DeepPartial and covers when it is worth the complexity.
When to reach for Partial, and when not to
Partial fits these cases:
- Update or patch payloads, usually as
Partial<Omit<T, "id">>. - Configuration overrides merged over defaults, such as
function configure(overrides: Partial<Config>). - Form or draft state where fields are filled over time.
- Test factories that build an object from a few overrides.
It is a poor fit when the "optional" fields are not truly independent. Suppose a payment needs either cardNumber or iban, but never neither. Partial<Payment> allows an empty object, so the type no longer enforces the rule. In such cases model the alternatives explicitly with a union of object types.
Also prefer a separate named type when a patch has different semantics from the entity. If clients may send null to clear a field, Partial<User> does not say so, and a dedicated type such as { email?: string | null } documents the contract.
Exercise
Given interface Product { sku: string; title: string; price: number; }, write the parameter type for updateProduct(product: Product, changes: ...) so that callers may change title and price in any combination, may pass an empty object, and cannot pass sku. Then say what exactOptionalPropertyTypes changes for the call updateProduct(p, { price: undefined }).
Show answer
Use Partial<Omit<Product, "sku">>. Omit removes sku first, then Partial makes title and price optional, so {}, { title: "x" } and { title: "x", price: 5 } are valid and { sku: "z" } is an excess-property error. By default { price: undefined } compiles, and merging it would overwrite the price with undefined at runtime. With exactOptionalPropertyTypes enabled, that call is a compile error.
Exercise
Why does const x: Partial<{ color: string }> = { colour: "red" } fail, and does Partial<{ a: { b: number } }> accept { a: {} }?
Show answer
The first fails because the literal has an unknown property colour (an excess property check). A variable holding the same object would instead fail the weak type check, because it shares no properties with the target. The second does not accept { a: {} }. Partial is shallow, so a may be omitted but, when present, must contain the required b: number.