Using javascript libs without TypeScript definition

Say you wanted to use Telerik’s HTML5 Report Viewer  in your TypeScript definition files and you cannot find the TypeScript definition file.   You are probably doing:

module ViewModel {

export class ReportViewModel {

constructor() {
this.init();
}

init() {

$(() => {

var reportViewer = jQuery("#reportViewer1");
if (reportViewer) {
reportViewer.telerik_ReportViewer({
serviceUrl: "/api/reports/",
templateUrl: 'kendo/ReportViewer/templates/telerikReportViewerTemplate-8.1.14.804.html',
reportSource: {
report: "Telerik.Reporting.Examples.CSharp.ProductCatalog, CSharp.ReportLibrary",
parameters: {
CultureID: "en"
}
}
});
}

});
}
}
}

However, without the TypeScript definition file, Visual Studio will complain that telerik_ReportViewer is not a property of jQuery.

You have two options:

1. Create an ambient variable for jQuery


declare var jQuery;

export class ReportViewModel {

just before the export class definition.  The disadvantage of this method is that you lose all IntelliSense for jQuery in Visual Studio.

2. Second option is to cast the result of the jQuery selector to any as follows:


var reportViewer = <any>jQuery("#reportViewer1");
if (reportViewer) {

The advantage of this method is that you continue working as normal without losing intellisense for jQuery.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s