Make property optional if all its children are optional

Viewed 145

How do I make properties of an object optional:

  • if it is already optional
  • if it isn't optional, if all its inner properties are optional

The would be for it to work recursively for a whole record, so the properties of the properties of the root of my objects are also rendered optional if the rules are matched.

type Given = {
  p1: string;
  p2?: number;
  p3: {
    p31: string;
  };
  p4: {
    p41?: string;
  };
  p5: {
    p51: string;
    p52: number;
  };
  p6: {
    p61: string;
    p62?: number;
  };
  p7: {
    p71?: string;
    p72?: number;
  };
  p8?: {
    p81: string;
  };
  p9: {
    p91: {
      p911: {
        p9111?: string;
      };
    };
  };
}

I should get following:

type Expected = {
  p1: string;
  p2?: number;
  p3: {
    p31: string;
  };
  p4?: {
    p41?: string;
  };
  p5: {
    p51: string;
    p52: number;
  };
  p6: {
    p61: string;
    p62?: number;
  };
  p7?: {
    p71?: string;
    p72?: number;
  };
  p8?: {
    p81: string;
  };
  p9?: {
    p91?: {
      p911?: {
        p9111?: string;
      };
    };
  };
}

I already tried some solutions with extends but I can't find a way to match the fact that all properties match a condition.

Thanks for your help.

0 Answers
Related