I am currently working on a typescript application in VS Code and have moved sensitive information to a .env file:
# .env file
NAME='foobar'
Within my main app, which utilizes the .env file, I have included the dotenv npm package. Additionally, I am attempting to pass an environment variable as a parameter to a function in another file.
App.ts
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)
}
An issue arises at this point, as there are red squiggly lines under process.env.NAME in the app.ts file
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)
To address this, I have used
await printName(process.env.NAME || '')
However, I feel like there may be a better way to handle this. Any suggestions would be greatly appreciated, especially since I am new to Typescript.