This project is read-only.

Create instance of object for use with ambient class declaration

Topics: General, Language Specification
Mar 14, 2013 at 11:17 PM
I'm trying to map some existing code to typescript using ambient declarations. I have an example like this:
var data = require("./common.js");

declare class User{
    public name: String;
    public getName():String;

import User = data.User;

export var group = {
    test: (t) =>{
        var user:User = new User("test");
Where common.js is
var userProxy = function(){
    return function(name){ = name;
        this.getName = function(){
            "use strict";
            return name;

module.exports.User = userProxy();
This runs in my unit test (via nodeunit) just fine.

However, I'm confused as to how to move the ambient class declaration into somewhere else so that it is reusable among classes? I need an instance of the user, which comes from an instance common.js via the require. Ambient declarations, I'm assuming, must map directly to the variable name that they are defining. With CommonJs though all fields are modularized. On top of that, if I try and do something like this
import data = module("common");
Then it compiles to
var data = require("common")
Which never finds my local common.js.

Does anyone have any suggestions on how to do properly do this?
Mar 18, 2013 at 4:06 PM
Generally, when working with external modules, there are a few options.

If you're importing another file using the import data = module("common") syntax, the name "common" can be as you put it, or it can start with a "." as in "./common". The latter is a way to say "the module file named common in the current directory".

You're trying to load the .js file directly. Instead, what you want to do is to load the types and declarations for what will be in that .js file. If you look at the Node example in the samples directory, you'll see an example of this. The HttpServer.ts references the node.d.ts to get the declarations of the modules it can load, and then it proceeds to load the one named "http". If you look in node.d.ts in the same directory, you'll see the "http" module being declared (it starts with "declare module "http" "). The declares are a way to give type information to the compiler about a symbol that will be visible at runtime.

The .js files aren't referenced directly. Instead, we output code that module loaders like Common.js/Require.js/AMD/etc can use. They will handle the loading of the module with the name you've declared.