#New to ts

25 messages · Page 1 of 1 (latest)

hardy blade
#

How do I fix this error? migrating from js.


const URL = process.env.mongourl;
const mongoClient = new MongoClient(URL, { useNewUrlParser: true, useUnifiedTopology: true });

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.

loud shadow
#
const URL = process.env.mongourl!;
#

if you're sure the environment variable is always there

hardy blade
#

it sometimes won't be there if the env file is not there, what do I do?

loud shadow
#

then the typescript error is correct

#

what should the app do when the env var is not there?

hardy blade
#

throw an error maybe?

#

war/inform the user somwhow

loud shadow
#

yeah if you make it throw an error

#

that should make typescript happy

hardy blade
#

hmm ok

#

wait the error went away itself? hmm?

loud shadow
#

?!

#

how?!

hardy blade
#

I had changed the js requires to imports

#

(I am migrating to ts from js)

loud shadow
#

thonk

hardy blade
#

soo er do I need to handle the case where it might be undefined or leave it?

loud shadow
#

you probably should

hardy blade
#

ok ty

#

something like this good?

if (URL) {
    const mongoClient = new MongoClient(URL, { useNewUrlParser: true, useUnifiedTopology: true });
} else {
    throw new Error("Env file not configured properly. 'mongourl' not defined.")
}
loud shadow
#

not really

#

you can't access mongoclient outside the if that way

#

just do if (!URL) { throw the error }

hardy blade
#

ah yea sorry