Skip to content

Instantly share code, notes, and snippets.

@cefn
Created January 29, 2022 09:04
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 cefn/da31cbe51d16816035f2a8940339328a to your computer and use it in GitHub Desktop.
Save cefn/da31cbe51d16816035f2a8940339328a to your computer and use it in GitHub Desktop.
Env Vars with enforcement and typing
import * as dotenv from 'dotenv';
dotenv.config();
const VARS = {
API_TOKEN: 'an API token',
API_URL: 'a URL for an endpoint',
} as const;
for (const [varname, description] of Object.entries(VARS)) {
if (typeof process.env[varname] !== 'string') {
throw new Error(`Please set the env var ${varname} to ${description}`);
}
}
export const {
API_TOKEN,
API_URL,
} = process.env as {
[k in keyof typeof VARS]: string;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment