How to implement TypeScript deep partial mapped type not breaking array properties

前端 未结 4 2139
遇见更好的自我
遇见更好的自我 2020-12-24 01:16

Any ideas as to how might apply TypeScript\'s Partial mapped type to an interface recursively, at the same time not breaking any keys with array return types?

The fo

4条回答
  •  感情败类
    2020-12-24 01:57

    With TS 2.8 and conditional types we can simply write:

    type DeepPartial = {
      [P in keyof T]?: T[P] extends Array
        ? Array>
        : T[P] extends ReadonlyArray
          ? ReadonlyArray>
          : DeepPartial
    };
    

    or with [] instead of Array<> that would be:

    type DeepPartial = {
      [P in keyof T]?: T[P] extends (infer U)[]
        ? DeepPartial[]
        : T[P] extends Readonly[]
          ? Readonly>[]
          : DeepPartial
    };
    

    You might want to checkout https://github.com/krzkaczor/ts-essentials package for this and some other useful types.

提交回复
热议问题