Get started TypeScript with Knockout JS in Visual Studio 2015

In recent ASP.NET MVC Web application I am working on, I need to write lots of knockout code for data binding. The code started to become very messy. It would be hard for colleagues later to maintain it. There are also some other missing features for JavaScript coding in general. For example, if I want to rename a variable, there is no refactoring feature like we have for C# in Visual Studio.

One good solution comes to mind was using TypeScript. It’s basically another layer above JavaScript. It helps us write strongly typed code and TypeScript complier will help us compile into standard JavaScript. And since TypeScript is just a superset of JavaScript, we can still mix normal JS code with TypeScript code.

Let’s start to create a simple application to wire up TypeScript with Knockout in Visual Studio 2015.

Step1: Open VS 2015 and create a empty ASP.NET Web Application.

Step2: Add a folder called Scripts under solution. And then add a new TypeScript(.ts) file

TS

Step 3: Write some simple TypeScript code:

dddd

If  you press “Show All Files” button, you will see the auto-generated js file for your TypeScript code.

fdafsaf

Step 4: Create a new HTML web page called Default.html. And then drag the the .ts file into Header.

ddd

You can see that Visual Studio automatically referenced the .js file instead of assoicated .ts file.

Set Default.html page as the Start page and run the application. You should get a popup says “stranger”.

Now we get a Hello World TypeScript application to work. The next step is to see how to wire up knockout.

Step 5: Install Knockout JS from Nuget package manager.

Now we come to a very important concept: Type Definition File. In order to write TypeScript code for any external JavaScript libraries such as Angular and Knockout. We need relevant Type Definition Files. What these Type Definition Files do is describing the interfaces of external JS libraries.

Step 6: Go to Nuget Package Manager and search for “typescript knockout”. You will find knockout.TypeScript.DefinitelyTyped package. After intalling it, we get a typing folder with the Type Definition File(.d.ts) under Scripts folder.

fdsfa

fffff

Step 7: Let’s see how to use it.

Drag knockout.d.ts file into our .ts script file,  we get the reference to the Type Definition File. It looks like comment. But it is actually how TypeScript references Type Definition File.

ggggg

Step 8:  Change exisintg code into TypeScript-style knockout JS code.

eeee

qqqq

Run the application, you will see our knockout application working as expected.