Search code examples
javascriptparse-platformtypescript

Parse.com with TypeScript: Extend Parse.Object


Disclaimer: I know, Parse.com shuts down it's hosted service. Still, we will continue to use the framework for a while, so this question is still important to us.

Recently, I started playing around with TypeScript and figured it might enhance my productivity for parse cloud code a lot. So I did some testing and was successfully able to use typescript to write cloud functions and so on. I even included the typing definition for parse via typings.

However, I still don't get one thing: How can I extend Parse.Object in a type-safe manner?

In normal js I would write:

var Foo = Parse.Object.extend("Foo", {
    // instance methods
}, {
    // static members
});

In order to get type safety, I would like to write something like this in typescript:

class Foo extends Parse.Object {
    // static members
    // instance methods
}

Is something like this possible? Am I missing out on something?


Solution

  • Yes, this is possible. There are a few steps necessary for this. First, you need to pass the classname to the parent constructor

    class Foo extends Parse.Object {
    // static members
    // instance methods
        constructor() {
            // Pass the ClassName to the Parse.Object constructor
            super('Foo');
        }
    
    }
    

    Furthermore, you need to register your class as an Parse object:

    Parse.Object.registerSubclass('Foo', Foo);
    

    After this, you can just use it for your query as:

    var query = new Parse.Query(Foo);
    query.find({
        success: obj: Foo[] => {
            // handle success case
        },
        error: error => {
            // handle error
        }
    });
    

    This also works for the new parse server open source project: https://github.com/ParsePlatform/parse-server