Skip to content

Track type of this in callbacks #968

Closed

Description

@danvk

There's an error (marked with <---) in this snippet which Flow could potentially catch:

class RemoteFile {
  url: string;
...
  promiseXHR(xhr: XMLHttpRequest): Q.Promise<[any, Event]> {
    var url = this.url;
    var deferred = Q.defer();
    xhr.addEventListener('load', function(e) {
      if (this.status >= 400) {
        deferred.reject(this.status + ' ' + this.statusText);
      } else {
        deferred.resolve([this.response, e]);
      }
    });
    xhr.addEventListener('error', function(e) {
      deferred.reject(`Request for ${this.url} failed: ${this.status}`);  // <---
    });
    this.numNetworkRequests++;
    xhr.send();
    return deferred.promise;
  }
}

The problem is that this inside the addEventListener callback refers to the XMLHttpRequest object (I believe) and not the RemoteFile class. The latter has a url property but not a status property, whereas the former has status but not url. Clearly this code isn't right!

Flow doesn't complain, though. It thinks this has type any in the event listener.

Where possible, the DOM declarations should indicate the type of this in callbacks to prevent this sort of mistake.

For example, Google's Closure Compiler provides an @this annotation. You can see an example of this in action in the declaration for Array.prototype.find.

Activity

  1. samwgoldman commented on Oct 22, 2015

    @samwgoldman
    Member

    Ref #452

  2. danvk commented on Oct 22, 2015

    @danvk
    ContributorAuthor

    Closing as a dupe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions