2

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 ?

Amin Taghikhani
  • 684
  • 1
  • 8
  • 22

1 Answers1

1

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} 
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35