Over a million developers have joined DZone.

Validating all observables w/ Knockout validation and Typescript

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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,

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Derik Whittaker, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}