Creating types for process.env with Zod
In this blog post, we will explore how to use Zod, a powerful TypeScript-first schema validation library, to create globally defined TypeScript types for environment variables in a project. Let’s get straight to the code.
environment.d.ts
| |
First we define environmentVariables, a Zod schema. This schema specifies the shape and validation rules for a set of environment variables that your application requires. In this case each of these variables is expected to be of type string.
The next part of the code introduces a global declaration. Here’s a breakdown of the code:
declare global: This is a TypeScript declaration that allows us to modify or extend global types.
namespace NodeJS: The NodeJS namespace provides a way to declare types specifically for Node.js environments.
interface ProcessEnv extends z.infer
Important part here is that by extending the ProcessEnv interface with z.infer