Recursive Partial<T> in TypeScript

With the landing of Conditional Types in 2.8, we can now declare a recursive partial type as follows.

type RecursivePartial<T> = {
  [P in keyof T]?:
    T[P] extends (infer U)[] ? RecursivePartial<U>[] :
    T[P] extends object ? RecursivePartial<T[P]> :
    T[P];
};

Reference:

http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html


you could make your own mapping type, like this:

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

enter image description here

Unfortunately, this does not work for array-typed fields. There does not seem to be a way to do conditional type mapping yet either; i.e. limit to primitives. See https://github.com/Microsoft/TypeScript/pull/12114#issuecomment-259776847 Its possible now, see other answer.


I've made a library, tsdef that has many common patterns / snippets like this.

For this case, you can use it like the following:

import { DeepPartial } from 'tsdef';

let o: DeepPartial<{a: number}> = {};

Tags:

Typescript