Typescript-不同文件中的模块函数引用-“;找不到符号“;

Typescript - module functions reference in different file - "could not find symbol"

本文关键字:引用 符号 函数 找不到 模块 文件 Typescript-      更新时间:2023-09-26

如果答案很简单,或者我读错了typescript文档,我很抱歉,但是。。

我有一个模块:

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

谢谢。

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

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

这在Client.ts 中起到了作用

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

获取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
    }
}

在这种情况下,您使用的是外部模块加载程序,typescript需要知道它的amd(requirejs/浏览器)还是commonjs(节点/服务器端)

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