Skip to content

Instantly share code, notes, and snippets.

@bencmbrook
Last active December 18, 2023 23:19
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 bencmbrook/c16ffb225d640d9ce34f7a64ce8f11cf to your computer and use it in GitHub Desktop.
Save bencmbrook/c16ffb225d640d9ce34f7a64ce8f11cf to your computer and use it in GitHub Desktop.
createDefinedPropertyObject.ts
type NonUndefined<T> = T extends undefined ? never : T;
/**
* Create an object with a single property, if the value is not undefined.
* Guarantees you don't have `{ myKey: undefined }` in your object.
*
* @param keyName the name of the key
* @param value the value which may be undefined
* @returns an object which should be spread into a parent object
*
* Usage:
* ```ts
* {
* ...createDefinedPropertyObject('myKey', myValue),
* }
* ```
*
* Results in: `{ myKey: myValue }` or `{}`, if `myValue` is undefined.
*/
function createDefinedPropertyObject<K extends string, V>(
keyName: K,
value: V
): { [key in K]: NonUndefined<V> } | undefined {
return value === undefined
? undefined
: ({ [keyName]: value } as { [key in K]: NonUndefined<V> });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment