Published on

How to Define types for process.env in TypeScript?

How to Define types for process.env in TypeScript?

How to Define types for process.env in TypeScript?

How to Define Types for process.env in TypeScript?

TypeScript is a typed superset of JavaScript that adds optional static type checking to the language. This means that TypeScript can help you catch errors in your code before you even run it. One of the benefits of using TypeScript is that it can help you define types for your environment variables. This can make your code more readable and maintainable.

What is process.env?

The process.env object is a global object in Node.js that contains environment variables. Environment variables are key-value pairs that can be used to store configuration information for your application.

How to define types for process.env in TypeScript

To define types for process.env in TypeScript, you can create a file called environment.d.ts and declare the types of your environment variables in the global namespace.

For example, the following code defines the types for the PORT and DATABASE_URL environment variables:

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      PORT: string;
      DATABASE_URL: string;
    }
  }
}

Once you have defined the types for your environment variables, you can use them in your TypeScript code like any other type. For example, the following code uses the PORT environment variable to set the port number for your application:

import { config } from "dotenv";

config();

const PORT = process.env.PORT;

const app = express();

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

I hope this helps!