Using TypeScript with PhoneGap / Cordova Plugins

I ran into a small hurdle since I wanted to start using the Google Analytics Cordova plugin , but I am composing all my javascript assets in TypeScript. Here is a good example of the specific problem I am facing:

window.plugins.googleAnalyticsPlugin.startTrackerWithAccountID("UA-xxxxxxx-x"); 

TypeScript balks at window.plugins , throwing a compilation error:

The 'plugins' property does not exist for a value of type 'Window'.

And that makes sense. However, I cannot get around this using the declare var window; operator declare var window; as this creates a duplicate identifier for the window.

+4
source share
1 answer

Step one is to extend the Window interface, which you can do as follows:

 interface Window { plugins: any; } 

This does not mean compiler errors, but if you do not expand the definition, it means no automatic completion. Now this line will work:

 window.plugins.googleAnalyticsPlugin.startTrackerWithAccountID("UA-xxxxxxx-x"); 

You can use this extended version of the definition to make something more visible and get automatic completion (and so that your checks are also verified).

 interface GoogleAnalyticsPlugin { startTrackerWithAccountID(accountId: string): void; } interface Plugins { googleAnalyticsPlugin: GoogleAnalyticsPlugin; } interface Window { plugins: Plugins; } 
+16
source

Source: https://habr.com/ru/post/1491955/


All Articles