Created
January 29, 2022 09:04
-
-
Save cefn/da31cbe51d16816035f2a8940339328a to your computer and use it in GitHub Desktop.
Env Vars with enforcement and typing
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
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