添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Development TypeScript | 3 Min Read

How to Fix Undefined Environment Variable (ENV) Type Issues in TypeScript

Learn how to correctly type and add auto-complete functionality to your Environment Variables in your TypeSript projects via one simple file!

When working with environment variables (ENVs) inside a TypeScript application, you’ll likely come across an error such as this one ` Invalid type "string | undefined" of template literal expression ` . This is because TypeScript can’t be 100% sure the value will be present when the code is run so therefore the value has the potential of being ` undefined ` .

However, if we’re 100% sure the ENV will be defined when the code is run whether that be in production or local development, we can resolve this issue and have our ENVs always typed correctly without ` undefined ` . We can do this by adding a new type declaration file to our project which will tell TypeScript the type it’ll be 100% of the time and remove the potential of it being ` undefined ` .

Also, by doing this, we’ll gain the ability to be able to autocomplete our ENV values in our IDE because TypeScript will become aware of the potential values present in our environment variables. So, without further ado, let’s look at how to implement this.

Creating our Type Declaration File

To create the type declaration file we’ll need for this, create a new file in the root of your project called ` env.d.ts ` and add the below code to it.

./env.d.ts
1declare namespace NodeJS {
2 export interface ProcessEnv {
3 // 👇 Replace with your ENV names and types
4 YOUR_ENV_NAME: YOUR_ENV_TYPE;
5 }
6}
ts

Inside this file, you can add your ENVs and their respective types to the ` ProcessEnv ` interface. For example, you could do something like this.

./env.d.ts
1declare namespace NodeJS {
2 export interface ProcessEnv {
3 ACCESS_TOKEN: string;
4 SESSION_TOKEN: string;
5 ENVRIONMENT: "development" | "production";
6 }
7}
ts

Updating our ` tsconfig.json `

The final step we need to perform is to update our ` tsconfig.json ` file to include our new type declaration file ( ` env.d.ts ` ), this will allow TypeScript to use our new type declaration file to type the ENVs present in our environment. To include the file in your ` tsconfig.json ` , add the below code to your ` tsconfig.json ` file.

./tsconfig.json
1{
2 "include": ["env.d.ts"]
3}
json