Skip to content

Instantly share code, notes, and snippets.

@aparx
Last active March 3, 2023 07:25
Show Gist options
  • Save aparx/bac509b9fdddeaac8ce59264afa2a455 to your computer and use it in GitHub Desktop.
Save aparx/bac509b9fdddeaac8ce59264afa2a455 to your computer and use it in GitHub Desktop.
DeepPartial & DeepReadonly utility types
export type Primitives =
| number
| string
| boolean
| bigint
| symbol
| undefined
| null;
export type DeepReadonly<TInput> = TInput extends Primitives | Function
? TInput
: TInput extends (infer TElement)[]
? ReadonlyArray<TElement>
: TInput extends Map<infer TKey, infer TVal>
? ReadonlyMap<TKey, TVal>
: TInput extends Set<infer TElement>
? ReadonlySet<TElement>
: TInput extends object
? { readonly [P in keyof TInput]: DeepReadonly<TInput[P]> }
: Readonly<TInput>;
export type DeepPartial<TInput> = TInput extends Primitives | Function
? TInput
: TInput extends ReadonlyArray<infer TElement>
? ReadonlyArray<DeepPartial<TElement>>
: TInput extends (infer TElement)[]
? DeepPartial<TElement>[]
: TInput extends ReadonlyMap<infer TKey, infer TVal>
? ReadonlyMap<DeepPartial<TKey>, DeepPartial<TVal>>
: TInput extends Map<infer TKey, infer TVal>
? Map<DeepPartial<TKey>, DeepPartial<TVal>>
: TInput extends ReadonlySet<infer TElement>
? ReadonlySet<DeepPartial<TElement>>
: TInput extends Set<infer TElement>
? Set<DeepPartial<TElement>>
: TInput extends { [key: PropertyKey]: any }
? DeepPartialObject<TInput>
: TInput extends Readonly<infer TObject>
? Readonly<DeepPartialObject<TObject>>
: Partial<TInput>;
type DeepPartialObject<TObject> = {
[P in keyof TObject]?: DeepPartial<TObject[P]>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment