打字稿 - 模块函数引用不同的文件 - “找不到符号”

时间:2013-08-29 09:27:21

标签: javascript typescript web-essentials

如果对此的回答很简单,或者我错误地阅读了打字稿文档,那么道歉,但是......

我有一个模块:

module Utils{

    export function MyFunction(str: string):string {
        return // something to do with string
    }

}

我想在另一个.ts文件(Clients.ts)中使用它,所以在顶部我添加一个引用并尝试使用它:

/// <reference path="Utils.ts" />
Utils.MyFunction(str);

但是得到以下错误:

/*

Compile Error. 
See error list for details
 [path]/Clients.ts(26,39): error TS2095: Could not find symbol 'Utils'.
 [path]/Clients.ts(30,49): error TS2095: Could not find symbol 'Utils'.
error TS5037: Cannot compile external modules unless the '--module' flag is provided.


*/

有人可以解释我做错了吗?

使用VS2012,使用Web Essentials和TypeScript 0.9.1

感谢。

2 个答案:

答案 0 :(得分:5)

自己找到答案。我实际上在寻找的是一个类的静态方法。如下所示:

class Utils {

    static MyFunction(str: string): string {
        return //... do something with string
    }
}

这在Client.ts中起作用

/// <reference path="Utils.ts" />
var x = Utils.MyFunction(str);

答案 1 :(得分:2)

您获得的错误error TS5037: Cannot compile external modules unless the '--module' flag is provided.不是您的代码所能获得的。

只有在文件的根级别导出某些内容时,才能获得此功能。例如

export module Utils{ // Notice the export keyword 

    export function MyFunction(str: string):string {
        return // something to do with string
    }

}

在这种情况下,您使用外部模块加载器,打字稿需要知道它是amd(requirejs / browser)还是commonjs(节点/服务器端)

PS:我制作了一个关于这个主题的视频:http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1