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

前端 未结 4 2141
遇见更好的自我
遇见更好的自我 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 02:05

    I started with @krzysztof's answer but have since been iterating on it when I come across edge cases. Specifically the edge cases below, based on the given value of the base object (i.e. T[P]):

    • any
    • any[]
    • ReadonlyArray
    • Map
    • Set
    type NonAny = number | boolean | string | symbol | null;
    type DeepPartial = {
      [P in keyof T]?: T[P] extends NonAny[] // checks for nested any[]
        ? T[P]
        : T[P] extends ReadonlyArray // checks for nested ReadonlyArray
        ? T[P]
        : T[P] extends (infer U)[]
        ? DeepPartial[]
        : T[P] extends ReadonlyArray
        ? ReadonlyArray>
        : T[P] extends Set // checks for Sets
        ? Set>
        : T[P] extends Map // checks for Maps
        ? Map>
        : T[P] extends NonAny // checks for primative values
        ? T[P]
        : DeepPartial; // recurse for all non-array and non-primative values
    };
    

    The NonAny type is used to check for any values

提交回复
热议问题