在TypeScript中,我可以使用RequireJS导入模块:
import Foo = require("common/Foo"); // Foo is one of my TypeScript exported classes.
class Bar {
// Wooohooo! I can use Foo here, complete with intellisense!
new Foo(1, "ab").zanzibar();
}
但有时候我不想加载Foo直到真正需要它,就像调用一些函数一样:
class Bar {
doSomething() {
// OK, now we need Foo. Import it.
require(["common/Foo"], Foo => {
// Use Foo here.
// Uh oh. No intellisense -- where did my static typing disappear to?
new Foo(1, "ab").zanzibar(); // Works at runtime, but no intellisense. :-(
});
}
}
有没有办法告诉TypeScript Foo是什么类型的?
答案 0 :(得分:2)
从Modules in TypeScript documentation(参见“可选模块加载”):
declare var require;
import Zip = require('./ZipCodeValidator');
if (needZipValidation) {
require(['./ZipCodeValidator'], (x: typeof Zip) => {
if (x.isAcceptable('...')) { /* ... */ }
});
}