【发布时间】:2018-01-04 10:46:06
【问题描述】:
关于如何将 TypeScript 的 Partial 映射类型递归地应用于接口,同时不破坏任何具有数组返回类型的键的想法?
以下方法还不够:
interface User {
emailAddress: string;
verification: {
verified: boolean;
verificationCode: string;
}
activeApps: string[];
}
type PartialUser = Partial<User>; // does not affect properties of verification
type PartialUser2 = DeepPartial<User>; // breaks activeApps' array return type;
export type DeepPartial<T> = {
[ P in keyof T ]?: DeepPartial<T[ P ]>;
}
有什么想法吗?
更新: 已接受的答案 - 目前更好、更通用的解决方案。
找到了一种临时解决方法,其中涉及类型和两个映射类型的交集,如下所示。最显着的缺点是您必须提供属性覆盖来恢复被污染的键,即具有数组返回类型的键。
例如
type PartialDeep<T> = {
[ P in keyof T ]?: PartialDeep<T[ P ]>;
}
type PartialRestoreArrays<K> = {
[ P in keyof K ]?: K[ P ];
}
export type DeepPartial<T, K> = PartialDeep<T> & PartialRestoreArrays<K>;
interface User {
emailAddress: string;
verification: {
verified: boolean;
verificationCode: string;
}
activeApps: string[];
}
export type AddDetailsPartialed = DeepPartial<User, {
activeApps?: string[];
}>
【问题讨论】:
-
看起来你需要mapped conditional types,它们还不是 TypeScript 的一部分 ????。如果您希望将其充实作为答案,请告诉我。
-
明白了。您现在有什么建议作为解决方案?
-
最直接的答案是手动声明一个
DeepPartialUser接口与你想要的(也就是放弃)。或者,您可以执行类似interface DeepPartialUser extends DeepPartial<User> { activeApps?: string[]; }之类的操作,它可以保护损坏的特定阵列,同时保留其他阵列。 -
放弃需要维护两个不受约束的数据模型元素,但无法知道它们之间的关系。我宁愿从基础模型中检索一个局部模型,确保派生接口的单一事实来源
-
根据您的建议找到了一个 hacky 解决方法,如更新后的问题所示,您对此有何看法。当然可以改进,不是吗?
标签: typescript recursion partial mapped-types