Created
April 14, 2024 15:40
-
-
Save meiazero/ffad53ef6b3f3638a1a1715ff25e084b to your computer and use it in GitHub Desktop.
Trick to extend node.js native `ProcessEnv` interface to include your own environment variables with zod
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 { z } from "zod"; | |
| export const envVariables = z.object({ | |
| // your env variables like: | |
| HOST: z.string(), | |
| PORT: z.number().int().positive(), | |
| }); | |
| // Parse the environment variables to ensure they match the schema | |
| envVariables.parse(process.env); | |
| // Extend the ProcessEnv interface with the inferred type from envVariables | |
| declare global { | |
| namespace NodeJS { | |
| interface ProcessEnv extends z.infer<typeof envVariables> {} | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment