Skip to content

Instantly share code, notes, and snippets.

@Evanion
Created April 25, 2024 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Evanion/62f4657fbf6195da6289612b647b0674 to your computer and use it in GitHub Desktop.
Save Evanion/62f4657fbf6195da6289612b647b0674 to your computer and use it in GitHub Desktop.
Excludes `null`, in an object, and replaces it with `undefined` in a way that TypeScript understands it.
type ExcludeNull<T> = {
[K in keyof T]-?: null extends T[K] ? Exclude<T[K], null> : T[K];
};
/**
* Filters out any `null` values and makes them `undefined`.
* It also filters out the type of the object so the TS parser understands it.
* @param obj Object containing null types
* @returns
*/
export function excludeNull<Data extends Record<string, unknown>>(
obj: Data
): ExcludeNull<Data> {
Object.keys(obj).forEach((key) => {
// Check if the property is null
if (obj[key] === null) {
// If null, delete the property
delete obj[key];
}
});
return obj as ExcludeNull<Data>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment