Type Safe process.env

Published

I've found myself copy and pasting the same TypeScript snippet to add type-safety for process.env.<X> references in my various projects. I figured I should just write a brief blog post to help myself with this in the future.

Use this snippet to override process.env types:

1declare global {
2 namespace NodeJS {
3 interface ProcessEnv {
4 // Replace `KEY` with your env variables!
5 KEY: string;
6 }
7 }
8}
9
10export {};
1declare global {
2 namespace NodeJS {
3 interface ProcessEnv {
4 // Replace `KEY` with your env variables!
5 KEY: string;
6 }
7 }
8}
9
10export {};

Recipe:

  • Create a types.d.ts file at the root of the project
  • Insert the above snippet
    • Make sure to replace KEY with your env variables!
  • Add ./types.d.ts to the includes array in tsconfig.json