First experiences with TypeScript in Visual Studio 2013 using jQuery and KnockoutJS libraries

For one customer, I wanted to create a POC to showcase the compile-time error checking advantages of TypeScript.

First of all: Visual Studio 2013 with Cumulative Update 4 is not enough to get the latest version of TypeScript, so you need to download it from TypeScript 1.4 for Visual Studio 2013. It is required to correctly compile some of the TypeScript definition files that will be included later.

Then it's possible to start creating a new MVC application. It includes by default NuGet packages for some common JavaScript libraries: jQuery, jQuery UI and Knockout JS, but it's possible to remove them or add new ones. These libraries are included by the MVC shared view _Layout.cshtml via bundle inclusions. The bundles are defined in App_Start/BundleConfig class.

To be able to use these libraries in our TypeScript files (getting compile-time error checking and Intellisense suggestions) it's necessary to include the .d.ts files, that are definition files with the purpose of use non-TypeScript libraries in TypeScript files. They can be found in the GitHub project DefinitelyTyped, but it's better to include them via NuGet packages (search for example for TypeScript jQuery, and so on).

Now following for example the example in TypeScript and JQuery example, I create a MyApp.ts file and paste the code here below (it's also possible to download the file MyApp.ts (392B):

/// <reference path="jquery.d.ts" />
 
class Person {
 
constructor(name:string)
{
this.name=name;
}
name: string;
}
 
function greeter (person:Person){
return "hallo "+person.name;
}
 
var person=new Person("bert");
 
 
$(document).ready(function(){
var message = greeter(person);
$("#status")[0].innerHTML=message;
});


As this file is created, a correspondent JavaScript file MyApp.js should be created.

Without including this file in the Visual Studio solution, it's possible to include this file in our shared _Layout, or better include it in one bundle.

At this point running the program, an alert, result of our MyApp code, should be displayed.


Notes so far in my research:

  • even if we have the .d.ts file, the original JavaScript files must be included. The .d.ts file is only a bridge to allow to use these libraries in the new TypeScript files, as described in Using jQuery plugin in TypeScript.
  • the .d.ts file can have a version different from the included JavaScript files, so when including these modules, it can be tricky to select the correct NuGet version. Else we can have a misalignment between the real JavaScript file and the hints suggested by the TypeScript compiler.

The better reference I have found to learn TypeScript is the TypeScript Handbook.

Add comment

Loading