Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly use dotenv / .env for passing parameters in typescript?

I’ve got a typescript app that I’m editing via VS Code. I’ve removed sensitive information into a .env file:

# .env file
NAME='foobar'

In my main app, that is consuming the .env file, I have installed the dotenv npm package. I’m also trying to pass the environment variable as parameter to a function in another file.

App.ts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import {
    printName
} from "./printStuff"
import * as dotenv from 'dotenv'
dotenv.config()

await printName(process.env.NAME)

printStuff.ts

export async function printName(name: string){
    console.log(name)
}

This is where the issue occurs. I get the dreaded red squiggly lines under process.env.NAME in the app.ts

string | undefined
Argument of type 'string | undefined' is not assignable to parameter of type     'string'.
  Type 'undefined' is not assignable to type 'string'.ts(2345)

I’ve been able to solve this via

    await printName(process.env.NAME || '')

but this seems off to me. Is there a better way of doing this?
My apologies in advance, I’m new to Typescript.

>Solution :

Using a non-null assertion operator:

await printName(process.env.NAME!); // ok

but keep in mind this is just an assertion for TypeScript to tell it that it isn’t undefined. It can still be undefined at runtime if you don’t set the env variable and can cause issues.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading