Skip to main

Recursive Partial Type

  • typescript
  • util
  • type
1 min read

Sometimes we would like to derive a deeply nested partial/optional type from an existing type (without modifying it). This simple type util can come in handy for that:

type RecursivePartial<T> = {
  [P in keyof T]?: RecursivePartial<T[P]>;
};

Usage

type PointCoord = {
  x: number;
  y: number;
};

type PointColor = {
  r: number;
  g: number;
  b: number;
};

type PointData = {
  coord: PointCoord;
  color: PointColor;
};

//  Err :( coord, color are partial not it's nested props
type partialPoint = Partial<PointData>;

//  All props including the nested ones like x, y are Partial
type nestedPartialPoint = RecursivePartial<PointData>;

Original Source: Stackoverflow