Answer the question
In order to leave comments, you need to log in
Why doesn't typescript see environment variables?
I included the .env file in the main app.ts file like this
import * as dotenv from 'dotenv';
dotenv.config();
but in another file I want to connect bd and use environment variablesexport const db = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER ,
process.env.DB_PASSWORD,
{
host: 'localhost',
dialect: 'postgres',
models: [__dirname + 'models']
}
);
/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:587
return new TSError(diagnosticText, diagnosticCodes);
^
TSError: ⨯ Unable to compile TypeScript:
src/db.ts:4:11 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
4 process.env.DB_NAME,
~~~~~~~~~~~~~~~~~~~
at createTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:587:12)
at reportTSError (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:591:19)
at getOutput (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:921:36)
at Object.compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1189:32)
at Module.m._compile (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1295:42)
at Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Object.require.extensions.<computed> [as .ts] (/home/ihor/Test Task by Komah Ihor/node_modules/ts-node/src/index.ts:1298:12)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Module.require (internal/modules/cjs/loader.js:957:19)
[nodemon] app crashed - waiting for file changes before starting...
Answer the question
In order to leave comments, you need to log in
We read carefully
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
export const DB_NAME = process.env.DB_NAME ?? "default_database";
I should have just written import { Sequelize } from 'sequelize-typescript';
export const db = new Sequelize(
`${process.env.DB_NAME}`,
`${process.env.DB_USER}` ,
`${process.env.DB_PASSWORD}`,
{
host: 'localhost',
dialect: 'postgres',
models: [__dirname + 'models']
}
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question