3

I had the impression that adding environment variables to environment.d.ts would ensure that they had the proper types.

I have @types/node as a dev-dependency, and have an environment.d.ts containing the following

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      DATABASE_URL: string;
    }
  }
}

export {};

However, when I attempt to use DATABASE_URL, e.g. in

import PgPromise from "pg-promise";
const db = PgPromise()(process.env.DATABASE_URL || "");

I'm still getting the error

error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string | IConnectionParameters<IClient>'.
Type 'undefined' is not assignable to type 'string | IConnectionParameters<IClient>'.

Is there any way to ensure that DATABASE_URL is of type string, as opposed to string | undefined? Am I missing something?

blub
  • 582
  • 7
  • 17
  • Please [edit] your question to show where you're using that value. You can always use `as string` to convince TypeScript it's a string, see [this answer](https://stackoverflow.com/a/52892398/215552) to [using process.env in TypeScript](https://stackoverflow.com/q/45194598/215552) – Heretic Monkey Aug 28 '21 at 19:25
  • Just edited the question to show where I'm using the value! – blub Aug 28 '21 at 19:32
  • To anyone that reads, sorry that I didn't include more details in my question. Was trying to limit it to what was relevant, but it seems I omitted the actual cause of the error as well. – blub Sep 09 '21 at 18:52

1 Answers1

7

The error was coming from the fact that I was using ts-node.

I was using nodemon / ts-node, and ts-node uses files / include / exclude to determine what files to monitor. Because I didn't specify these, it wasn't able to detect my files.

I fixed it by adding

{
  ...,
  "ts-node": {
    "files": true
  },
  "include": ["src/**/*.ts", "environment.d.ts"]
}

to my tsconfig.json

blub
  • 582
  • 7
  • 17