Attempting to load .env environment variables using Typescript.
Here are my .env
and app.ts
files:
//.env
DB_URL=mongodb://127.0.0.1:27017/test
// app.ts
import * as dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';
dotenv.config();
mongoose.connect(process.env.DB_URL, config);
When running the app.ts
with the ts-node src/app.ts
command, an error is thrown:
Unable to compile TypeScript:
src/app.ts:50:18 - error TS2769: No overload matches this call.
Overload 1 of 3, '(uris: string, callback: (err: MongoError) => void): Promise<typeof import("mongoose")>', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
Overload 2 of 3, '(uris: string, options?: ConnectionOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
50 mongoose.connect(process.env.DB_URL, config);
However, adding the following if statement resolves the issue:
//app.ts
import * as dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';
dotenv.config();
//Add this code
if (!process.env.DB_URL) {
process.exit(1);
}
mongoose.connect(process.env.DB_URL, config);
Example app listening at http://localhost:3000
Mongoose default connection is open to mongodb://127.0.0.1:27017/test
The question remains: why does this error not occur in the code below?