Skip to content

Instantly share code, notes, and snippets.

@dankochetov
Last active January 20, 2022 10:35
Show Gist options
  • Save dankochetov/adb31d3b22b414d0b64230af94e80dd2 to your computer and use it in GitHub Desktop.
Save dankochetov/adb31d3b22b414d0b64230af94e80dd2 to your computer and use it in GitHub Desktop.
getEnvVar and getEnvFlag type-safe functions
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