Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kaybutter
Last active August 13, 2018 09:20
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 kaybutter/8e8dedfe40263265c67f6e876eacc9ce to your computer and use it in GitHub Desktop.
Save kaybutter/8e8dedfe40263265c67f6e876eacc9ce to your computer and use it in GitHub Desktop.
Null to Undefined
/**
* Converts an optional type that accepts null to an optional type
* that accepts undefined
*/
type NullToUndefined<T> = T extends null ? undefined : T
/**
* Converts an object type with optional properties that allow null to a
* type with properties that allow undefined instead. Non-Optional
* properties will remain unchanged.
*/
type WithoutNullValues<T> = { [key in keyof T]: NullToUndefined<T[key]> }
/** Replaces null values with undefined */
function withoutNullValues<T>(object: T): WithoutNullValues<T> {
const objectKeys = Object.keys(object)
const patchedObject = objectKeys.reduce((accumulator, key) => {
accumulator[key] = object[key] !== null ? object[key] : undefined
return accumulator
}, {})
return patchedObject as WithoutNullValues<T>
}
// examples
const sourceObject = {
someOptional: null,
someNonOptional: 'test',
someChileObject: {
someOptional: null,
someNonOptional: 'test',
}
}
const fixedObject = withoutNullValues(object)
fixedObject.someChildObject.someOptional // undefined and not null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment