DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on

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';
Enter fullscreen mode Exit fullscreen mode

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

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

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;
};
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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>;
Enter fullscreen mode Exit fullscreen mode

Dict type:

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

About us:

  1. We study large open source projects and provide free architectural guides.

  2. We have developed free, reusable Components, built with tailwind, that you can use in your project.

  3. We analyse open-source code and provide courses so you can learn various advanced techniques and improve your skills. Get our courses.

  4. Subscribe to our Youtube Channel to get the insights from the open-source projects, where we review code snippets.

Image description

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

Top comments (0)