Partial Updates Apply Typed Patches
Model PATCH payloads with Partial<T> so clients may set any subset of keys, merge with spread, and remember nesting still replaces whole objects.
Code
interface ServiceConfig {
name: string;
replicas: number;
memoryMb: number;
labels: string[];
}
// Partial<T>:所有键可选,恰好是 PATCH 载荷的形状
type ConfigPatch = Partial<ServiceConfig>;
function applyPatch(current: ServiceConfig, patch: ConfigPatch): ServiceConfig {
return { ...current, ...patch };
}
const base: ServiceConfig = {
name: 'orders-api',
replicas: 3,
memoryMb: 512,
labels: ['prod'],
};
// 只改想要的键:类型保证不出现未知键或错误值类型
const scaled = applyPatch(base, { replicas: 5, memoryMb: 1024 });
console.log('scaled:', scaled.name, scaled.replicas, scaled.memoryMb, scaled.labels.join(','));
// 空补丁:没有键被覆盖,语义上是原样返回
const untouched = applyPatch(base, {});
console.log('untouched intact:', untouched.replicas === base.replicas && untouched.memoryMb === base.memoryMb);
// Partial 不递归:嵌套字段仍要整对象替换,这是有意保留的简单语义
const relabeled = applyPatch(base, { labels: ['prod', 'edge'] });
console.log('relabeled:', relabeled.labels.join('+'));Output
Captured from a sandboxed run of this snippet in the build pipeline.
scaled: orders-api 5 1024 prod
untouched intact: true
relabeled: prod+edgePATCH as Partial
ConfigPatch = Partial
Empty and full patches
The untouched run passes {} and the intact check prints true: spread of an empty object changes nothing. The scaled run sets replicas and memoryMb only, leaving name and labels as-is.
Non-recursive by design
Nested fields still replace whole objects — Partial does not descend. The relabeled run replaces labels wholesale, which the code comment marks as the intentional, simple semantic.
Interactive Tools for This Topic
FAQ
- Why does Partial<T> fit PATCH payloads?
- A PATCH may set any subset of keys; Partial makes every field optional so the type admits exactly those subsets.
- What does the demo mean by "Partial is not recursive"?
- Nested objects still replace as whole values — a patch cannot update one field deep inside a nested object; only top-level keys merge via spread.
Report a problem with this exampleOpens a pre-filled issue on GitHub.