Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TypeScript with PhoneGap/Cordova Plugins

I'm running into a bit of a roadblock as I would like to start using the Google Analytics Cordova plugin but I'm composing all of my javascript assets in TypeScript. Here is a good example of the specific problem I'm having:

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

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

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

And that makes complete sense. However, I can't get around this by using a declare var window; statement, as that creates a duplicate identifier for window.

like image 479
Rob Lauer Avatar asked Dec 04 '22 10:12

Rob Lauer


1 Answers

Step one is to extend the Window interface, which you can do like this:

interface Window {
    plugins: any;
}

This will mean no compiler errors, but unless you extend the definition it means no auto-completion. So this line will now work:

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

To take things up a notch and get yourself some auto-completion (and to get your spellings checked too) you can use this extended version of the definition.

interface GoogleAnalyticsPlugin {
    startTrackerWithAccountID(accountId: string): void;
}

interface Plugins {
    googleAnalyticsPlugin: GoogleAnalyticsPlugin;
}

interface Window {
    plugins: Plugins;
}
like image 188
Fenton Avatar answered Dec 09 '22 14:12

Fenton