Skip to content

Instantly share code, notes, and snippets.

@kiliman
Created August 11, 2023 14:43
Show Gist options
  • Save kiliman/32a37e906fcaf1dd0c2853037ffbf897 to your computer and use it in GitHub Desktop.
Save kiliman/32a37e906fcaf1dd0c2853037ffbf897 to your computer and use it in GitHub Desktop.
Type helpers
export type MakeOptional<Type, Key extends keyof Type> = Omit<Type, Key> &
Partial<Pick<Type, Key>>;
export type PickNullable<T> = {
[P in keyof T as null extends T[P] ? P : never]: T[P];
};
export type PickNotNullable<T> = {
[P in keyof T as null extends T[P] ? never : P]: T[P];
};
export type OptionalNullable<T> = T extends object
? {
[K in keyof PickNullable<T>]?: OptionalNullable<Exclude<T[K], null>>;
} & {
[K in keyof PickNotNullable<T>]: OptionalNullable<T[K]>;
}
: T;
// expands object types one level deep
export type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
// expands object types recursively
// prettier-ignore
export type ExpandRecursively<T> =
T extends Date ? T // don't expand dates
: T extends object ?
T extends infer O ? { [K in keyof O]: ExpandRecursively<O[K]> }
: never
: T;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment