[Typescript] Tips: DeepPartial

Deep partials are SUPER useful and not natively supported by TypeScript. Here, I use one to help with mocking an entity in a (imaginary) test file.

 

type DeepPartial<T> = T extends Function
  ? T
  : T extends Array<infer InferredArrayMember>
    ? DeepPartialArray<InferredArrayMember>
    : T extends object
      ? DeepPartialObject<T>
        : T | undefined;

interface DeepPartialArray<T> extends Array<DeepPartial<T>> {}

type DeepPartialObject<T> = {
  [Key in keyof T]?: DeepPartial<T[Key]>
}

interface Post {
  id: string;
  comments: {value: string}[]
  meta: {
    name: string;
    description: string
  },
  call: Function
}

const post:DeepPartial<Post> = {
  id: "123",
  comments: [
    {value: "123"}
  ]
}

 

posted @ 2022-10-10 14:10  Zhentiw  阅读(153)  评论(0)    收藏  举报