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 ?

1
  • Yes, using a conditional check provides both type safety and runtime safety. Commented Sep 28, 2021 at 6:27

1 Answer 1

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} 
Sign up to request clarification or add additional context in comments.

2 Comments

this what I'm doing for now ,and my question is there a better approach ?
This is a better approach, you are doing both here type safety and runtime safety.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.