Blog
ProcessEnv type in next-runtime-env source code

ProcessEnv type in next-runtime-env source code

In this article, we analyse the ProcessEnv type found in next-runtime-env source code and review the StackOverflow answer and also Matt Pocock’s article.

ProcessEnv type

ProcessEnv is imported as shown below

import { ProcessEnv } from '../typings/process-env';

In the typings/process-env, you will find the below code:

import { type Dict } from './dict';
export type ProcessEnv = Dict<string>;

It is a Dict of type string, but Dict type is imported from /dict and has the below code

export type Dict<T> = {
 [key: string]: T | undefined;
};

Matt Pococok’s article

In the Total TypeScript article — How to strongly type process.env,
it is stated that “a common problem in TypeScript is that process.env doesn’t give you autocomplete for the environment variables that actually exist in your system” and Matt suggests two solutions:

- Augment the global type
- Validate at Runtime with t3-env

These approaches do not mention anything about defining your ProcessEnv types, but you will see this suggestion/accepted answer on Stackoverflow. Read further to find out.

Stackoverflow Accepted Answer

There was a question titled — using process.env in TypeScript on Stackverflow. It has 21 answers but I like the accepted answer more and you will similar approach in next-runtime-env source code.

The accepted answer tells you to define a ProcessEnv type with the below code:

export interface ProcessEnv {
 [key: string]: string | undefined
}

next-runtime-env has the same type, only difference is, the defined type is assigned to a variable named Dict.

import { type Dict } from './dict';
export type ProcessEnv = Dict<string>;

Dict type:

export type Dict<T> = {
 [key: string]: T | undefined;
};

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github — https://github.com/ramu-narasinga

My website — https://ramunarasinga.com

My Youtube channel — https://www.youtube.com/@thinkthroo

Learning platform — https://thinkthroo.com

Codebase Architecture — https://app.thinkthroo.com/architecture

Best practices — https://app.thinkthroo.com/best-practices

Production-grade projects — https://app.thinkthroo.com/production-grade-projects

References:

  1. https://github.com/expatfile/next-runtime-env/blob/development/src/typings/process-env.ts#L3

  2. https://www.totaltypescript.com/how-to-strongly-type-process-env

  3. https://stackoverflow.com/questions/45194598/using-process-env-in-typescript

  4. https://stackoverflow.com/a/45195359