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 us:
We study large open source projects and provide free architectural guides.
We have developed free, reusable Components, built with tailwind, that you can use in your project.
We analyse open-source code and provide courses so you can learn various advanced techniques and improve your skills. Get our courses.
Subscribe to our Youtube Channel to get the insights from the open-source projects, where we review code snippets.
Top comments (0)