Generate TypeScript type for nested partial objects and arrays
A custom TypeScript type named TNestedPartial has been created to produce a partial variation of an object or array, enabling optional properties at every level of nesting.
Check out the code snippet below:
export type TNestedPartial<T> = {
[K in keyof T]?: T extends Array<infer R> ? Array<TNestedPartial<R>> : TNestedPartial<T[K]>;
};
This type essentially goes through all keys of the original type T, making each property optional (?). If the current property happens to be an array, it recursively generates an array of partially nested types (Array<TNestedPartial>). Alternately, it applies TNestedPartial recursively to the nested property (TNestedPartial<T[K]>).
Such a type proves useful when creating partial representations of intricate nested data structures in TypeScript.