小编All*_*oyi的帖子

如何实现TypeScript深部分映射类型而不破坏数组属性

关于如何以递归方式将TypeScript的部分映射类型应用于接口的任何想法,同时不破坏任何具有数组返回类型的键?

以下方法还不够用:

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 ]>;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

更新:接受的答案 - 现在更好,更一般的解决方案.

我找到了一个临时解决方法,涉及类型和两个映射类型的交集,如下所示.最显着的缺点是你必须提供属性覆盖来恢复被污染的密钥,具有数组返回类型的密钥.

例如

type PartialDeep<T> = {
  [ P in keyof T ]?: PartialDeep<T[ P ]>;
}
type PartialRestoreArrays<K> = {
  [ P in …
Run Code Online (Sandbox Code Playgroud)

recursion partial typescript mapped-types

26
推荐指数
2
解决办法
8924
查看次数

标签 统计

mapped-types ×1

partial ×1

recursion ×1

typescript ×1