6
当涉及到以纯Javascript编写的声明文件和第三方库时,我没有在TypeScript中获得这些东西。比方说,我有以下的Javascript类:如何在TypeScript中使用声明文件
$ cat SomeClass.js
var SomeClass = (function() {
function SomeClass() {
}
SomeClass.prototype.method1 = function() {
return "some string";
};
return SomeClass;
})();
exports.SomeClass = SomeClass;
而且我想要得到它的类型检查,所以我创建声明文件是这样的:
$ cat test.d.ts
class SomeClass {
public method1(): string;
}
然后我想使用的类和声明文件中的某些代码:
$ cat main.ts
///<reference path="./test.d.ts"/>
import ns = module("./SomeClass");
function test(): string {
var sc = new ns.SomeClass();
return sc.method1();
}
当我尝试编译它,我得到这个:
$ tsc main.ts
main.ts(2,19): The name '"./SomeClass"' does not exist in the current scope
main.ts(2,19): A module cannot be aliased to a non-module type
main.ts(5,16): Expected var, class, interface, or module
从我所知道的情况来看,导入语句需要一个实际的TypeScript类来存在,并且引用语句不足以帮助编译器找出如何处理它。
我试图将其更改为
import ns = module("./test.d");
但没有骰子无论是。
唯一的办法我能得到这个实际编译和运行是使用要求语句,而不是进口的,就像这样:
$ cat main.ts
///<reference path="./node.d.ts"/>
///<reference path="./test.d.ts"/>
var ns = require("./SomeClass");
function test(): string {
var sc = new ns.SomeClass();
return sc.method1();
}
这段代码的问题是,打字稿没有运行任何类型检查。事实上,我可以完全删除线
///<reference path="./test.d.ts"/>
它并没有改变任何东西。但是,如果我删除require语句,我可以进行类型检查,但是由于没有require语句,因此代码在运行时崩溃。
$ cat main.ts
///<reference path="./test.d.ts"/>
function test(): string {
var sc = new SomeClass();
return sc.method1();
}
test();
$ node main.js
main.js:2
var sc = new SomeClass();
^
ReferenceError: SomeClass is not defined
...