有没有办法使用声明的TypeScript模块进行静态类型化?

时间:2014-08-24 11:42:34

标签: module typescript definitelytyped

我有一个需要连接到MongoDB的node.js的小型TypeScript应用程序:

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)
        {
        }
    }
}

现在,我知道我在连接回调上获得了Db类,但我无法找到明确键入db参数的方法Db 1}}类。我使用了mongodb的DefinitelyTyped定义文件,它是这样的:

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);
        [...]
    }
}

我尝试过这样导入:

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

但我收到以下错误:

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

有没有办法使用Db类从模块外部进行显式输入?

1 个答案:

答案 0 :(得分:1)

您是否尝试过像这样重新定位导入?以下编译并为我运行

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();