实现说明
全部逻辑都在函数 applyPatch中。
返回的是新建的值,不复用入参。
使用要点
- 把
applyPatch当作 API:导入它,其余代码可以忽略。
常见问题
applyPatch 会修改传入的参数吗?
不会。传入的任何东西都不会被写入,对共享数据调用是安全的。
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 applyPatch。
入口签名:export function applyPatch(base: Account, patch: DeepPartial<Account>)
核心语句
? { [K in keyof T]?: DeepPartial<T[K]> }
代码示例
export type DeepPartial<T> = T extends (infer U)[]
? DeepPartial<U>[]
: T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
export interface Account {
id: string;
profile: {
name: string;
address: { city: string; zip: string };
};
}
export function applyPatch(base: Account, patch: DeepPartial<Account>): Account {
return {
...base,
...patch,
profile: { ...base.profile, ...(patch.profile ?? {}) },
};
}