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.
CodePudding user response:
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.
CodePudding user response:
Any passed in env var could possibly be undefined, therefore you either need to guarantee in your code that it exists before passing it to printName
or make it optional in printName.
A few options could be:
const name = process.env.NAME
//Check name exists before using it
if (name) {
printName(name)
} else {
//Add some error handling. What should happen if name doesnt exist?
}
//Alternatively, if name is undefined, do error handling
if (!name) {
//Add some error handling. What should happen if name doesnt exist?
}
printName(name)
//Make name optional in printName, possibly risky if you arent handling
// what happens if name is undefined elsewhere
export async function printName(name?: string){
console.log(name)
}