Is there any way to use static typing with declared TypeScript modules?

I have this little TypeScript app for node.js that needs to connect to a MongoDB:

module Engine
{
    export class EngineCore
    {
        public launch()
        {
            var mongo = require('mongodb');
            var client = mongo.MongoClient;

            client.connect('mongodb://localhost:27017/', (error, db) => {this.onDBConnect(db)});
        }

        private onDBConnect(db)
        {
        }
    }
}

Now, I know that I'm getting a Db class on connect callback, but I can't figure out the way to explicitly type the db argument to the Db class. I'm using a DefinitelyTyped definition file for mongodb, it goes like this:

declare module "mongodb" {

    export class MongoClient {
        constructor(serverConfig: any, options: any);

        static connect(uri: string, options: any, callback: (err: Error, db: Db) => void): void;
        static connect(uri: string, callback: (err: Error, db: Db) => void): void;
    }

    export class Db {
        constructor (databaseName: string, serverConfig: Server, dbOptions?: DbCreateOptions);
        [...]
    }
}

I've tried importing it like this:

module Engine
{
    import MongoDB = require('mongodb');
    [...]
}

But I'm getting the following error:

error TS2136: Import declarations in an internal module cannot reference an external module.

Is there any way to use the Db class for explicit typing from outside the module?

Upvotes: 0

Views: 379

Answers (1)

KnarfaLingus
KnarfaLingus

Reputation: 466

Have you tried re-positioning the import like this? the below compiles and runs for me

import mongo = require('mongodb');


 module Engine
{
    export class EngineCore
    {
        public launch()
        {
            var client = mongo.MongoClient;

            client.connect('mongodb://localhost:27017/', (error, db) => {

                    this.onDBConnect(db);
                });
        }

        private onDBConnect(db:mongo.Db)
        {
            console.log("connected");
        }
    }

}

var x = new Engine.EngineCore();
x.launch();

Upvotes: 1

Related Questions