5

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?

3
  • 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 to using process.env in TypeScript Commented Aug 28, 2021 at 19:25
  • Just edited the question to show where I'm using the value! Commented Aug 28, 2021 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. Commented Sep 9, 2021 at 18:52

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

This was it! Also the default behaviour of include was "src/**/*" so if your environment.d.ts is inside src, then enabling only the ts-node/files flag also works. Did a little digging and on their website and they state that this flag helps with "certain typechecking failures" as in our case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.