I'm trying to load .env environment variable using Typescript.
This is 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 I run app.ts
using ts-node src/app.ts
command, throwing this error
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);
But when I add below if statement, it works well
//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
I want to know why is this error not thrown in below code?