ctusch ctusch - 1 year ago 61
TypeScript Question

How to add a property with a custom type to Node's Global interface

I can't figure out how to add a property of MongoDB's

type to Node's Global interface. Here is what I currently have:

// file vendor.d.ts
/// <reference types="mongodb" />

declare namespace NodeJS{
interface Global {
db: Db

I get the following compiler error:

vendor.d.ts(5,9): error TS2304: Cannot find name 'Db'.

If I change the type to
or even
I get no error. Also, I can access the
type in my other code just fine. What am I doing wrong?

Answer Source

This is because you are consuming the mongodb type declarations incorrectly

Try this

import  {Db} from 'mongodb';

declare global {
  namespace NodeJS {
    interface Global {
      // Always name constructors with an initial capital letter.
      Db: typeof Db;

Please note that by adding a top level import we have changed the source type/goal of the importing file, making it a module. This is also what necessitates the declare global block wrapping the declarations. Inside a module, all declarations are lexically scoped to the module body. The declare global syntax was introduced to enable modifying the ambient global scope from within a module.

Because it is now a module, it also changes the semantics of any code other code in the file so I recommend that you move it out of vendor.d.ts.

For example, you might create a file called augmentations.d.ts and place it in the root of your project.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download