4
votes

Basically, I want to define an interface for an AMD js module which is accessed from a ts file. The problem is that the module import in ts does not return the anonymous class that is typically defined and returned in a AMD js module. So I can not use 'new' to instantiate them.

I have an AMD module (it's the main file of a package and I refer to it as 'a/main' in other modules) which is like this:

main.js

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

  return a;
});

To use a/main in typescript, I have created a.d.ts, in which a is defined like this:

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

Then I have a typescript file in which I want to use a:

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();

The problem is that modules are not new-able. so, var x=new a(); won't work.

Could you suggest the best way to declare "a/main" module?

Note: I have many files like a.js and prefer to find a way to write .d.ts files in a way so that I do not need to change all my .js files, i.e., changing the .js files is the last resort.

3

3 Answers

0
votes

You will probably need TypeScript 0.9.1 for this solution to work:

a.js (you called it main.js)

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

  return a;
});

a.d.ts (placed beside 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();
1
votes

Your definition for main can include the class for a:

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

I added an example function to show that when you use the declare keyword you don't need any implementation - just the method signatures.

This is an example using this declaration.

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

If you want to import an module that you defined in a js file instead of typescript then you should not use the typescript module import syntax.

Instead simply use the standard AMD syntax of importing a module as if you were writing Javascript inside your otherfile.ts . This will however give you a variable that is not strongly typed.

Update Sample:

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 
});