TypeScript和RequireJS - 我的静态输入在哪里?

时间:2014-03-14 19:46:00

标签: requirejs typescript

在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是什么类型的?

1 个答案:

答案 0 :(得分:2)

Modules in TypeScript documentation(参见“可选模块加载”):

示例:在require.js中加载动态模块

declare var require;
import Zip = require('./ZipCodeValidator');
if (needZipValidation) {
    require(['./ZipCodeValidator'], (x: typeof Zip) => {
        if (x.isAcceptable('...')) { /* ... */ }
    });
}