Skip to content

Instantly share code, notes, and snippets.

@scamden
Last active January 12, 2025 17:59
Show Gist options
  • Save scamden/4010eed296ecdfbbd513c97d3b54b0a8 to your computer and use it in GitHub Desktop.
Save scamden/4010eed296ecdfbbd513c97d3b54b0a8 to your computer and use it in GitHub Desktop.
/**
* Converts null values in a simple JS value to undefined.
* Useful to parse responses from graphql and erase the (arguably) useless distinction between
* a property not having been requested vs. having been requsted and truly not existing.
*
* Will ignore dates, regexes, functions, maps, and sets
* but any other object type will have it's properties recursively converted.
*/
export type NullToUndefined<T> = T extends null
? undefined
: T extends Primitive | Function | Date | RegExp
? T
: T extends Array<infer U>
? Array<NullToUndefined<U>>
: { [K in keyof T]: NullToUndefined<T[K]> };
export function nullToUndefined<T>(value: T): NullToUndefined<T> {
if (value === null) {
return undefined as NullToUndefined<T>;
}
return (
Array.isArray(value)
? value.map(nullToUndefined)
: typeof value === 'object' &&
!isDate(value) &&
!isRegExp(value) &&
!isMap(value) &&
!isSet(value)
? mapValues(value, nullToUndefined)
: value
) as NullToUndefined<T>;
}
export type Primitive = string | number | symbol | bigint | boolean | null | undefined;
function isDate(value) {
return value instanceof Date && !isNaN(value.getTime());
}
function isRegExp(value) {
return value instanceof RegExp;
}
function isMap(value) {
return value instanceof Map;
}
function isSet(value) {
return value instanceof Set;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment