Skip to content
jshacks.dev
TypeScript

How to Make All Properties Optional Deeply

Build a DeepPartial type in TypeScript 6 that makes every nested property optional, and learn how it treats arrays, functions and Date values.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, JavaScript, Node.js, Vite and npm logos.

The built-in Partial<T> makes the top-level properties of an object optional, and nothing else. If your configuration object has a server property that holds a port and a host, Partial lets you omit server, but if you supply server you still have to supply both fields inside it. That is rarely what you want for overrides, test fixtures or patch payloads. This post shows how to make all properties optional deeply with a recursive mapped type, how to handle arrays, functions and built-in objects correctly, and where the approach stops being safe. The examples target TypeScript 6.x, and they work the same way in the native TypeScript 7 compiler. The reference for the building blocks is the mapped types chapter of the TypeScript handbook.

Why Partial is shallow

Partial<T> is defined in the standard library as a homomorphic mapped type: { [P in keyof T]?: T[P] }. The ? modifier is added to each key of T, and the value type T[P] is copied as it is. Nothing looks inside T[P], so a nested object keeps all of its required fields.

config-shallow.tsTypeScript
interface Config {
  name: string;
  server: {
    host: string;
    port: number;
  };
}

const override: Partial<Config> = {
  server: { host: "example.test" },
};

The compiler rejects this, because server is present but lacks port.

Text
config-shallow.ts(8,3): error TS2741: Property 'port' is missing in type '{ host: string; }' but required in type '{ host: string; port: number; }'.

The fix is a type that applies the same transformation at every level.

The basic recursive type

A mapped type can refer to itself. Wrap each property in the same type, and TypeScript expands it lazily as it checks your values.

deep-partial.tsTypeScript
export type DeepPartial<T> = {
  [P in keyof T]?: DeepPartial<T[P]>;
};

For an object, each key becomes optional and each value goes through DeepPartial again. For a primitive such as string, the mapped type over a primitive returns the primitive unchanged, because homomorphic mapped types do not transform primitives. That is the base case that stops the recursion, and you do not have to write it.

use-basic.tsTypeScript
import type { DeepPartial } from "./deep-partial.ts";

interface Config {
  name: string;
  server: {
    host: string;
    port: number;
  };
}

const override: DeepPartial<Config> = {
  server: { host: "example.test" },
};

console.log(override.server?.host);
Text
example.test

The assignment now compiles, and the optional chaining in the last line is required because server itself became optional.

What happens to arrays

The homomorphic mapped type also handles arrays and tuples in a useful way. When T is an array type and the mapped type is homomorphic over a type parameter, TypeScript maps over the element type and returns an array. So DeepPartial<string[]> is (string | undefined)[], and the elements of an object array become deeply partial.

arrays.tsTypeScript
import type { DeepPartial } from "./deep-partial.ts";

interface Team {
  members: { id: number; name: string }[];
}

const patch: DeepPartial<Team> = {
  members: [{ id: 1 }, { name: "Ada" }],
};

console.log(patch.members?.length);
Text
2

Notice what the type permits. Because the ? modifier is applied to the array elements as well, the element type includes undefined when exactOptionalPropertyTypes is off, so [undefined, { id: 1 }] also type checks. If that bothers you, you can special case arrays, which the next section does.

Handling functions and built-in objects

The basic type has a real flaw. A function is an object type, and a mapped type over a function type produces an object with no call signature, so a method becomes a useless {} shaped thing. Built-in classes such as Date, Map and RegExp suffer in the same way, because the mapped type walks their method names and makes all of them optional.

A better definition stops at the types that should be treated as leaves.

deep-partial-safe.tsTypeScript
type Leaf =
  | string
  | number
  | boolean
  | bigint
  | symbol
  | null
  | undefined
  | Date
  | RegExp
  | ((...args: never[]) => unknown);

export type DeepPartial<T> = T extends Leaf
  ? T
  : T extends readonly (infer U)[]
    ? DeepPartial<U>[]
    : T extends Map<infer K, infer V>
      ? Map<K, DeepPartial<V>>
      : T extends Set<infer U>
        ? Set<DeepPartial<U>>
        : { [P in keyof T]?: DeepPartial<T[P]> };

This version is a conditional type, so it is distributive over unions, which is what you want for properties typed string | undefined or for discriminated unions. Leaves pass through untouched. Arrays become arrays of deeply partial elements without adding undefined. Maps and sets keep their collection types. Everything else falls to the object case.

use-safe.tsTypeScript
import type { DeepPartial } from "./deep-partial-safe.ts";

interface Job {
  id: number;
  runAt: Date;
  retry: (attempt: number) => boolean;
  options: { timeout: number; tags: string[] };
}

const patch: DeepPartial<Job> = {
  runAt: new Date("2026-01-01T00:00:00Z"),
  options: { tags: ["nightly"] },
};

console.log(patch.runAt?.toISOString());
Text
2026-01-01T00:00:00.000Z

With the simple version, patch.runAt would have been a mapped object without a working toISOString call signature, and the call would not compile. The Leaf list is the part you tune for your own codebase. Add URL, Uint8Array or your own value classes if they should be replaced whole rather than patched.

Using it for real merges

A type is only a promise, so the runtime code that applies a deep partial has to be written to match. A shallow spread would overwrite nested objects instead of merging them. This small merge function follows the same rules as the type, and it treats arrays and non-plain objects as leaves.

merge.tsTypeScript
import type { DeepPartial } from "./deep-partial-safe.ts";

function isPlainObject(value: unknown): value is Record<string, unknown> {
  return (
    typeof value === "object" &&
    value !== null &&
    Object.getPrototypeOf(value) === Object.prototype
  );
}

export function mergeDeep<T extends Record<string, unknown>>(
  base: T,
  patch: DeepPartial<T>,
): T {
  const out: Record<string, unknown> = { ...base };
  for (const [key, value] of Object.entries(patch)) {
    if (value === undefined) continue;
    const current = out[key];
    out[key] =
      isPlainObject(current) && isPlainObject(value)
        ? mergeDeep(current, value)
        : value;
  }
  return out as T;
}

const base = { name: "app", server: { host: "localhost", port: 3000 } };
const merged = mergeDeep(base, { server: { port: 8080 } });
console.log(merged);
Text
{ name: 'app', server: { host: 'localhost', port: 8080 } }

The cast on the last line of the function is the honest cost here. The compiler cannot prove that a recursive merge of a deep partial returns a full T, so the function asserts it. Keep the assertion inside one small, well-tested function rather than spreading it through the code.

When the recursion gets heavy

Recursive conditional types are checked lazily, but a very deep or very wide object type can still slow the checker or hit the instantiation depth limit. If you see error TS2589, "Type instantiation is excessively deep and possibly infinite", the usual causes are a self-referential interface with no leaf, or a generic parameter that the compiler cannot narrow. The remedies are the ones the type already uses: stop at leaves, avoid unions of huge object types, and apply DeepPartial at the boundary of a function rather than to every internal type.

A second caution is that deep partial types describe input, not state. A value of type DeepPartial<Config> cannot be passed where a Config is required, and the compiler will tell you so. Convert at one point, with a merge function like the one above, and pass the merged full value onward.

Alternatives

Libraries such as type-fest ship a PartialDeep type with options for arrays and sets, and it is a reasonable choice if you already depend on it. Writing your own takes ten lines and lets you decide what counts as a leaf, which matters more than it first appears. If you only need two levels, a one-off type such as Partial<Config> & { server?: Partial<Config["server"]> } is easier to read than a recursive utility.

Testing the type

A utility type deserves a few assertions, because the failure mode is silent. If the recursion stops one level early, nothing breaks until a caller hits the missing level. You can pin the behavior with a small equality helper and a few compile-time checks, kept in a file that only the type checker reads.

deep-partial.test-d.tsTypeScript
import type { DeepPartial } from "./deep-partial-safe.ts";

type Equal<A, B> =
  (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
    ? true
    : false;

type Expect<T extends true> = T;

type Sample = { a: { b: { c: number } }; list: { x: string }[]; when: Date };

type _deep = Expect<
  Equal<DeepPartial<Sample>["a"], { b?: { c?: number } } | undefined>
>;
type _date = Expect<Equal<DeepPartial<Sample>["when"], Date | undefined>>;

If either assertion were false, the Expect constraint would fail and tsc would report the line. There is nothing to print, because the file exists only to be type checked. Keeping a handful of these next to the utility means a later edit to the Leaf list cannot quietly change what the type does.

Think about where the optionality ends up, too. Every level gets ?, so reading a deep value needs optional chaining all the way down. That is correct for a patch, since any level may be absent. If you find yourself writing long chains on a DeepPartial value, it is a sign that the value should have been merged into a full object earlier.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.