How to use environment variable in Typescript properly?

Viewed 1322

I'm trying to make a simple api using typescript and when I use any env variable I get an error from TS compiler Tells me that this could be undefined

example

// Not Working

const db = process.env.DB_URL   // This gives an error that the result could be a string or undefined

to fix this I have to make a type guard and check with if statement as follows

const db = process.env.DB_URL   

if (db){
  // ....
}


Is there a better approach to to such a thing instead of explicitly check for every variable ?

1 Answers

You can apply null check and keep it as string instead of defining two types:

const db: string = process.env.DB_URL ?? ''

// empty strings are falsy/falsey
if (db) { // do this}
else { //do this} 
Related