TypeScript: adding import means class can't be found?

时间:2015-07-28 22:14:58

标签: typescript

I'm having problems with multiple files in my TypeScript project, a NodeJS app.

I have a class, Foo, in the file Foo.ts which has a property, db, which I want to be a MongoDB client. The class is declared like so:

import mongodb = require( 'mongodb' );
class Foo
{
    public db:mongodb.MongoClient = null;
}

If the require() isn't there, I get a Cannot find namespace 'mongodb' error on the db property.

In another file, Bar.ts, I want to create a reference to the Foo class. It's declared like so:

/// <reference path="Foo.ts" />
class Bar
{
    public foo:Foo = null;
}

However, if the require() is in Foo.ts, I get the error Cannot find name 'Foo'. If the require() isn't there, everything works as expected, and Bar can access Foo

How can I get this to resolve properly? I've tried replacing the require() with a <reference /> pointing to the mongodb.d.ts, but I get the error in Application again (possibly because the module is declared like declare module "mongodb"?). I can't seem to get the right combination to get both Foo.ts and Bar.ts to compile.

I could just declare db as any, but I'd love to keep code completion.

1 个答案:

答案 0 :(得分:1)

The issue is that you're mixing namespaces and modules (formerly called internal and external modules). Namespaces are used for more traditional, older JavaScript development where you would attach objects to window. Modules are used when using a module system like CommonJS. Since this is a Node app, you're using modules.

Foo.ts should look something like this:

import mongodb = require('mongodb');
class Foo
{
    public db:mongodb.MongoClient = null;
}
export = Foo;

Then, in Bar.ts, instead of using a <Reference> tag use another require:

import Foo = require('./foo');
class Bar
{
    public foo:Foo = null;
}