Last active
December 18, 2023 23:19
-
-
Save bencmbrook/c16ffb225d640d9ce34f7a64ce8f11cf to your computer and use it in GitHub Desktop.
createDefinedPropertyObject.ts
This file contains 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 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