This project is read-only.

How to use Typescript with libraries like Ampersand.js that parse configs to build prototypes

Topics: General
Aug 10, 2014 at 10:53 AM
My question is how to use libraries like AmpersandJS or other libraries that parse configs to build your (class) objects (I'm not sure if this pattern has a name) with Typescript. For example Ampersand.JS uses a function (.extend) to build up a prototype based on your configuration:
        // This object contains the configuration that Ampersand uses to build my model.
        var config = {
            props: {
                firstName: 'string',
                lastName: 'string'

        // Create a Person model with getters, setters, validation etc. 
        var Person = AmpersandModel.extend(config);

        // A basic usage to create an instance of a Person object
        var myPerson = new Person({firstName:"John", lastName:"Doe"});
        myPerson.firstName = "NewJohn"; // runs the first name setter build by ampersand
I'm struggling how to use implement the above example with Typescript. With other libraries like Backbone, you can use the normal / straightforward Typescript approach:
        MyModel extends Backbone.Model{}
However, with libraries like Ampersand.JS I cannot use:
        Person extends AmpersandModel{}
as this would never execute the AmpersandModel's custom extend() code that builds the prototype based on the configuration passed to the extend() function.

I'm not sure what other libraries face this same problem, and what solutions they use. Any example of libraries that use the Ampersand's pattern could be of help.
Aug 11, 2014 at 10:05 AM
If you are doing custom extending work, you probably need to "declare" these new classes as extended from the base class.
 class AmpersandModel { }
 declare class Person extends AmpersandModel { }
You can use interfaces for this also (note also: interface types can be later merged, but classes cannot). The only other alternative I can think of is to redefined the global '__extends()' function as an option for that library (since I'm assuming a user would not be using the TS extends, which is the point of the library, correct?).