Thomas
Thomas

Reputation: 6670

Unfamiliar Syntax, TypeScript, Promises

I am working on understanding the Angular Google Maps (AGM) Library on GitHub, specifically a particular section in their lazy-map-api-loader.ts file:

this.promise = new Promise<void>((resolve: Function, reject: Function) => {
  (<any> window)[callbackName] = () => { // I've simplified this line a bit.
    resolve();
  };

  script.onerror = (error: Event) => {
    reject(error);
  };
});

Eventually, the above promise is returned to the caller of this method; however, the piece that I don't understand is the cast (?) (<any>window)[callbackName] = syntax, seen above.

It looks like the are trying to access a particular property on the window object (with the name equivalent to the value of callback) and assign the property to a function that will resolve the promise in which the definition of anonymous the function is found.

From what I can see, however, the the function that is assigned to that property is never called in the repository.

What is happening above?

Upvotes: 1

Views: 46

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

The <any> is just used to avoid any property access issues since the callback name doesn't actually exist on window. The bracket syntax is used because callbackName is a variable.

This would be the same as:

this._windowRef.getNativeWindow().angular2GoogleMapsLazyMapsAPILoader

...however this would result in an type error if you didn't cast to any. My guess is that callbackName is used since it's a lot easier to type and it's used multiple times.

As for when this actually gets called, See the script tag construction which will result in something like:

<script src="https://googleapis.com/maps?callback=angular2GoogleMapsLazyMapsAPILoader"</script>

Google APIs itself will call this callback function once the script finishes loading. The property needs to exist on window in order for it to be called.

Upvotes: 2

Related Questions