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

时间:2015-01-06 13:23:18

标签: typescript

我试图将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编译正常。我做错了什么?

2 个答案:

答案 0 :(得分:3)

您正在混合内部和外部模块。这会产生问题,因为app.ts文件中的module A.B与main.ts文件中的module A.B不在“相同的公共根”中。

混合模式

不是真的推荐......而且您无法从外部模块中补充内部模块...

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

答案 1 :(得分:0)

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

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语句。

相关问题