Type-Fest DeepPartial Merge Utility
Model patch updates with type-fest DeepPartial, merging partial trees into complete config objects while preserving nested key typing.
Code
import type { DeepPartial } from 'type-fest';
interface ServerConfig {
http: { port: number; bodyLimitMb: number };
db: { url: string; poolSize: number };
features: { auditLog: boolean; darkMode: boolean };
}
function mergeConfig<T extends object>(base: T, patch: DeepPartial<T>): T {
const result: Record<string, unknown> = { ...base };
for (const [key, patchValue] of Object.entries(patch)) {
const baseValue = (base as Record<string, unknown>)[key];
const bothObjects =
patchValue && typeof patchValue === 'object' && !Array.isArray(patchValue)
&& baseValue && typeof baseValue === 'object' && !Array.isArray(baseValue);
result[key] = bothObjects
? mergeConfig(baseValue, patchValue)
: patchValue;
}
return result as T;
}
const defaults: ServerConfig = {
http: { port: 3000, bodyLimitMb: 1 },
db: { url: 'postgres://localhost/app', poolSize: 10 },
features: { auditLog: true, darkMode: false },
};
const merged = mergeConfig(defaults, { http: { port: 8080 }, features: { darkMode: true } });
console.log(merged.http.port, merged.db.poolSize, merged.features.darkMode);What the code does
One way to read it: the functions baseValue and mergeConfig, doing all the work.
Iteration happens inside for (const [key, patchValue] of Object.entries(patch)) — everything outside it runs once.
What to watch for
- Plan for an install step:
type-festis a real dependency, resolved by the package manager.
Applying it
The main signature reads const baseValue = (base as Record<string, unknown>)
Statements that matter
const merged = mergeConfig(defaults, { http: { port: 8080 }, features: { darkMode: true } });
&& baseValue && typeof baseValue === 'object' && !Array.isArray(baseValue);
const baseValue = (base as Record<string, unknown>)[key];
Interactive Tools for This Topic
FAQ
- What does this need from the package registry?
- These are real dependencies: `type-fest`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.