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.
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
Delete this post? You can undo for 30 seconds.