Last active
January 20, 2022 10:35
-
-
Save dankochetov/adb31d3b22b414d0b64230af94e80dd2 to your computer and use it in GitHub Desktop.
getEnvVar and getEnvFlag type-safe functions
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 EnvVarName = | |
| 'FOO' | |
| 'BAR'; | |
type EnvFlagName = | |
| 'IS_FOO' | |
| 'IS_BAR'; | |
export function getEnvVar<T extends string = EnvVarName | EnvFlagName>( | |
name: T, | |
params?: { | |
default?: string; | |
}, | |
): string; | |
export function getEnvVar<T extends string = EnvVarName | EnvFlagName>( | |
name: T, | |
params?: { | |
default?: string; | |
optional: true; | |
}, | |
): string | undefined; | |
export function getEnvVar<T extends string = EnvVarName | EnvFlagName>( | |
name: T, | |
params?: { | |
default?: string; | |
optional?: true; | |
}, | |
): string | undefined { | |
const res = process.env[name] ?? params?.default; | |
if (typeof res === 'undefined') { | |
if (params?.optional) { | |
return undefined; | |
} | |
throw new Error(`Environment variable '${name}' is not defined`); | |
} | |
return res; | |
} | |
export function getEnvFlag<T extends string = EnvFlagName>(name: T): boolean { | |
const str = getEnvVar(name, { default: '0' }); | |
return ['1', 'true'].includes(str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment