TypeScript + AMD:如何在模块中声明匿名类?

时间:2013-04-09 01:32:52

标签: module dojo requirejs typescript amd

基本上,我想为从一个ts文件访问的AMD js模块定义一个接口。问题是ts中的模块导入不会返回通常在AMD js模块中定义和返回的匿名类。所以我不能用'new'来实例化它们。

我有一个AMD模块(它是一个包的主文件,我在其他模块中将其称为'a / main'),如下所示:

main.js

define(function(){   
  var a=function(){...}; //constructor
  a.prototype={...};//body   

  return a;
});

要在打字稿中使用/ main,我创建了 a.d.ts ,其中a的定义如下:

declare module "a/main"{
    //I don't know how to writ this part... 
}

然后我有一个打字稿文件,我想在其中使用:

otherfile.ts

///<reference path="a.d.ts"/>
import a=module("a/main"); //here a should refer to a inside the main.
//so I should be able to say:
var x=new a();

问题是模块不是新的。所以,var x = new a();不行。

您能否建议宣布“a / main”模块的最佳方式?

注意:我有很多文件,比如a.js,并且更喜欢找到一种方法来编写.d.ts文件,这样我就不需要更改所有的.js文件了,即,更改.js文件是最后的手段。

3 个答案:

答案 0 :(得分:1)

您对main的定义可以包括以下类:

declare module "a/main" {
    class a {
        exampleFunction(name: string) : void;
    }
}

我添加了一个示例函数来表明当你使用declare关键字时,你不需要任何实现 - 只需要方法签名。

这是使用此声明的示例。

import main = module("a/main");
var x = new main.a();

答案 1 :(得分:0)

如果要导入在js文件中定义的模块而不是typescript,则不应使用typescript模块导入语法。

而是简单地使用导入模块的标准AMD语法,就像在 otherfile.ts 中编写 Javascript 一样。但是,这将为您提供一个非强类型的变量。

更新示例:

require(["main.js"], function(main:any) {
    //This function is called when main.js is loaded.
    //the main argument will hold
    //the module value for "/main".
    var x=new main(); // what you wanted 
});

答案 2 :(得分:0)

您可能需要TypeScript 0.9.1才能使此解决方案正常工作:

a.js (你称之为main.js)

define(function(){   
  var a=function(){...}; //constructor
  a.prototype={...};//body   

  return a;
});

a.d.ts (放在a.js旁边):

declare class ClassA {
    // members of a ...
    toString():string;  // for example
}

declare var classA:typeof iModuleA;
export = classA;

<强> otherfile.ts

import a=require("a"); // at runtime, a.js is referenced while tsc takes a.d.ts
//so you should be able to say:
var x=new a();
相关问题