Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load dotenv in Typescript

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?

like image 256
wonderkids Avatar asked Jul 05 '20 04:07

wonderkids


1 Answers

From the error message, you can conclude that TypeScript expect the first parameter of mongoose.connect() to be a string but environment variables can be either string or undefined.

By adding the condition, you eliminate the possibility that process.env.DB_URL would be undefined when at the time you call mongoose.connect(process.env.DB_URL, config)

If you are certain that it will never be undefined, you can use TypeScript Non-null assertion operator

mongoose.connect(process.env.DB_URL!, config);

Tip:

Instead of

import * as dotenv from 'dotenv';
...
dotenv.config();

You can do as the following

import 'dotenv/config'

This will make sure environment variables are set before the next import statements, so you would only have to do this only once at the main file of your app.

like image 176
thammada.ts Avatar answered Oct 16 '22 01:10

thammada.ts