Created
November 18, 2024 13:58
-
-
Save Phryxia/b750706cc1a5bca90f800bf4b3ff0975 to your computer and use it in GitHub Desktop.
Smart option assigining code for TypeScript
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
/** | |
* Inject all key values written in userOptions | |
* If a key value doesn't exist, use the value from defaultOptions | |
* In this case, even if userOptions[key] is undefined, it overwrites if given | |
* If you want behavior identical to Object.assign, set `isUndefinedIgnored` to `true` | |
* | |
* @param userOptions 사용자가 입력할 부분적인 값 | |
* @param defaultOptions 기본적으로 제공할 값 | |
* @param isUndefinedIgnored undefined 값을 무시할 지 여부 | |
* @returns | |
*/ | |
export function fillOptions<T extends object>( | |
userOptions: Partial<T>, | |
defaultOptions: T, | |
isUndefinedIgnored = false, | |
) { | |
const out = { ...defaultOptions }; | |
for (const key in userOptions) { | |
if (isUndefinedIgnored && userOptions[key] === undefined) { | |
continue; | |
} | |
out[key] = userOptions[key]!; | |
} | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment