Search code examples
javascriptlocal-storagetypescriptlawnchair

Using lawnchair with Typescript


Got a simple problem, which was touched upon in a similar question around the "this" scope with typescript.

I have a storage service which wraps lawnchair for my local storage concerns. Now I am migrating this code over to Typescript I have come to an issue I cannot solve.

public GetAll(callback: Function) {
           Lawnchair({ name: this.storeName }, function () {
                this.all(callback);
            });
        };

Now in the example above lawnchair makes this become the actual store you are actioning, but Typescript will make it become the instance of the class you are using. So is there a way around this issue?

== Edit ==

Updated the question example slightly as to not confuse with the underlying lawnchair method and the surrounding classes method.

Here is the error I get when trying to compile:

The property 'all' does not exist on value of type 'LawnchairStorageService'

Which is correct, that method does NOT exist on the containing class instance, it exists within the context of the lawnchair closure scopes this.


Solution

  • As noted in the comments above, this compiles, and I think it ought to run:

    public GetAll(callback: Function) {
        return function (callback){
            Lawnchair({ name: this.storeName }, function () {
                this.all(callback);
            });
        }(callback);
    };
    

    ... but I suspect someone else may be able to weigh in with a more elegant solution.