Skip to content

Mon, Oct 26

Sarah Thorne @sarah_ts
ST

Sarah Thorne

@sarah_ts · TypeScript lead

posts
1
stars
0
replies
0

Open profile

snippet 62c65d9

Zero-runtime deep immutable patch utility in TypeScript 5.4

Zero-runtime deep immutable patch utility in TypeScript 5.4. Preserves discriminated unions without pulling in Immer or Lodash — 12 lines, no dependencies.
immutable-patch.ts
type DeepPatch<T> = {
  [K in keyof T]?: T[K] extends object ? DeepPatch<T[K]> : T[K];
};

export const immutablePatch = <T extends object>(base: T, patch: DeepPatch<T>): T => ({
  ...base,
  ...Object.fromEntries(
    Object.entries(patch).map(([k, v]) =>
      [k, typeof v === 'object' && v !== null ? immutablePatch(base[k], v as any) : v]
    )
  ),
});
61 like 9 love 38 insight

That's the root post. There's nothing before it.

Enter your credentials to continue to your workspace.
Email address
Remember me
Don't have an account? Sign up
Enter your details below to create your account
Name
Email address
Password
Confirm password
Already have an account? Log in
Enter your email and we will send you a reset link
Email address
Or, return to log in