Over a million developers have joined DZone.

Validating all observables w/ Knockout validation and Typescript

DZone 's Guide to

Validating all observables w/ Knockout validation and Typescript

· Web Dev Zone ·
Free Resource

Knockout js is an awesome MVVM framework for HTML/Javascript development and there is an extension library which performs data validation called Knockout.Validation which is an equally awesome library.  Today when doing some coding I needed to validate that all properties on a VM were valid. A quick search showed me this was very easy and should just work.  However, I am using Typescript and for all of its awesomeness it sometimes makes life a bit more challenging than expected.

To validate an entire observable all you should need to do is first tell the validation library that your vm is under validation by doing


and then you can simply call a .isValid() on your VM as such.


However, when doing this in Typescript I was getting the red squiggly as you see here.


At first I was not sure why, so I decided to take a peek at the source for the validation and I came across the code you see below.


As you can see, the highlighted yellow is where the .isValid() method is being added to object (obj == your passed in viiew model) so I KNOW that my view model has a .isValid.  Sure enough at runtime if I hit a breakpoint and did this.isValid() i would get the response I was expecting.  However, because .isValid() was being added to my VM dynamically (this is the amazing power of JavaScript) Typescript did not know about the method and it was causing compile time errors.

How to fix this?

The simple solution that I found was to ‘fake’ Typescript into thinking that the .isValid computed is on my VM from the start.  I did this by adding the following to my VM


Now you will notice that I am simply declaring the computed I am NO assigning it and that is ok.  In fact if you look at the generated output from the Typescript compiler you will NOT see a computed created for .isValid().  But this does not matter.  The Typescript compiler thinks it is there so you are free to use it off of your VM as you see here.


After adding my declaration for isValid() I was good to go and my code worked as expected both at code time and run time.

Till next time,


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}