ctusch ctusch - 2 months ago 13
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

Db
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
string
or even
Buffer
I get no error. Also, I can access the
Db
type in my other code just fine. What am I doing wrong?

Answer

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.