Created
April 25, 2024 09:51
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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