引用 d.ts 文件时找不到符号

Cannot find symbol when referencing d.ts file

我正在尝试将 Backbone.js 与我的 Typescript 代码一起使用。当我添加导入时 tsc 无法使用 child.ts(12,8): error TS2304: Cannot find name 'Animal'..

编译我的代码

这是 main.ts 文件:

export module A.B {
    export class Animal {

        constructor(argument) {
            // code...
        }

        go() : string {
            return 'snow';
        }
    }
}

这是引用它的 child.ts 文件:

/// <reference path="main.ts" />
/// <reference path="jquery.d.ts" />
/// <reference path="underscore.d.ts" />
/// <reference path="backbone.d.ts" />

import Backbone = require("backbone");

module A.B {
    class Snake {

        constructor(argument) {
            new Animal(argument).go();
        }
    }
}

如果我删除导入 child.ts 编译正常。我做错了什么?

您正在混合使用内部和外部模块。这会产生一个问题,因为 app.ts 文件中的 module A.B 与 main.ts 文件中的 module A.B 不在 "same common root" 中。

混合模式

不推荐...并且您不能从外部模块中补充内部模块...

main.ts(内部模块)

module A.B {
    export class Animal {

        constructor(argument) {
            // code...
        }

        go(): string {
            return 'snow';
        }
    }
} 

app.ts(外部 - 包含在 define 函数中)

/// <reference path="main.ts" />
/// <reference path="scripts/typings/backbone/backbone.d.ts" />

import Backbone = require("backbone");

module X {
    class Snake {

        constructor(argument) {
            new A.B.Animal(argument).go();
        }
    }
}

内部模块

您不能使用 import 语句,因此您必须自己加载模块(即在 script 标记中)。

main.ts(注意,我们没有 export 模块)

module A.B {
    export class Animal {

        constructor(argument) {
            // code...
        }

        go(): string {
            return 'snow';
        }
    }
}

app.ts

/// <reference path="main.ts" />

module A.B {
    class Snake {
        constructor(argument) {
            new Animal(argument).go();
        }
    }
}

使用外部模块!

您也可以在自己的代码中使用模块加载。一切都在全局范围之外。

main.ts

export class Animal {

    constructor(argument) {
        // code...
    }

    go(): string {
        return 'snow';
    }
}

app.ts

import Main = require("main");

class Snake {

    constructor(argument) {
        new Main.Animal(argument).go();
    }
}

以下是我最终解决问题的方法:

module AA.BB {
    export class Animal {

        constructor(argument) {
            // code...
        }

        go() : string {
            return 'snow';
        }
    }   
}

并且:

/// <reference path="Animal.ts" />
/// <reference path="../../../keyword-exploration/public/typescript/definitions/jquery.d.ts" />
/// <reference path="../../../keyword-exploration/public/typescript/definitions/underscore.d.ts" />
/// <reference path="../../../keyword-exploration/public/typescript/definitions/backbone.d.ts" />

module AA.BB {
    class Snake extends Backbone.View<Backbone.Model> {

        constructor(argument) {
            super(argument);
            new AA.BB.Animal({});

        }
    }   
}

请注意,Backbone.js 不需要 require 语句。