Olivier Refalo
Olivier Refalo

Reputation: 51535

TypeScript Javascript patterns

I am busy creating a meteor.d.ts to support my Typescript developments on the Meteor.js platform. Current status can be found here

With that said, I am having issues abstracting two typical javascript patterns.

The first one Template.myTemplate.events(eventMap), where myTemplate can be dynamically created by the user.

Second, the ability to map this to a different interface. Meteor uses the pattern a lot. For instance, when calling Meteor.methods(..methods..), the methods are given access to this.isSimulation() which is not visible anywhere else.

Kind of difficult to explain, so a look at the meteor documentation may help

Any idea how to declare these two patterns?

Thank you.

Upvotes: 3

Views: 457

Answers (1)

basarat
basarat

Reputation: 276195

MyTemplate solution Provide two interfaces to the user. One that he can use to add new templates to Template. Another to allow him to specify the features of a Template:

interface ITemplate{

}
interface ITemplateStatic{
    events:Function;
}

declare var Template:ITemplate; 

// the user's code: 
interface ITemplate{
    myTemplate:ITemplateStatic; 
}
Template.myTemplate.events({}); 

This solution To answer your second question about this. The only way to do that is to expose the signatures as an interface. It is then the responsibility of the typescript user to get the proper type if he needs it. There is no way to implicity specify the type of this inside a function.

declare module meteor{
    interface IMethod{
        // A simple sample 
        isSimulation:boolean; 
    }
}

declare var Meteor;

// the user experience
Meteor.methods({
  foo: function (arg1, arg2) {
    var item:meteor.IMethod = this;  
    console.log(item.isSimulation); // now the signature is enforced
    return "some return value";
  }
});

Ofcourse I leave the naming convention up to you :)

Upvotes: 2

Related Questions