So there is this new thing called TypeScript. Which is a pretty cool superset of plain old javascript that adds type support and with that a whole bunch more cool stuff like classes, interfaces and modules.

I like to use KnockoutJS for my pages, because.. well, it makes working with data-driven pages super easy! I also want to take advantage of all the cool stuff that TypeScript brings.

This example is by no means a finished and polished one, but it will get you started with Knockout and TypeScript. Lets take a look at the very basic test ViewModel (in TypeScript of course).

module VM {

declare var ko: any;

export class Test {
constructor (targetElement: HTMLElement) {
ko.applyBindings(this, targetElement);

public Name: any = ko.observable();

public NewName: any = ko.observable();

public ChangeName() {

I’ll point out one of the flaws that still need fixing in this example and that is the ANY keyword for knockout and its observables. By saying that something is of type any you lose all the type resolution that TypeScript gives us. If we look past that for now we have a fully functional Knockout viewmodel. Here is the HTML that goes with it:

<script type="text/javascript" src="~/Scripts/TypeScript/VM.js"></script>

<script type="text/javascript">
var testVm = new VM.Test(document.getElementById('testVmView'));

<div id="testVmView">
<p data-bind="text: Name"></p>
<input type="text" data-bind="value: NewName" /><button data-bind="click: ChangeName">Change</button>

One way to fix the any typing of the observables is we provide our own wrapper around knockout observable and let the wrapper provide type safe observables.

Sander Harrewijnen

Author Sander Harrewijnen

Als ontwikkelaar mag ik graag problemen oplossen en nieuwe functionaliteit bouwen. Vanuit mijn creatieve kant hou ik me ook graag bezig met hoe iets bij de eindgebruiker aankomt. Je kunt bij mij dus ook terecht voor de opmaak en layout van een oplossing. Als je mij wilt afleiden, dan lukt dat altijd met een coole nieuwe gadget. Dat is namelijk mijn andere passie.

More posts by Sander Harrewijnen
17 October 2012

Leave a Reply