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
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.
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.