KnockoutObservable <number> returns string when bound to typescript input
I am using knockout version 3.2.0 and its definitelyTyped definitions from nuget:
I have an input bound property (type number) with value binding, property definition:
export class SomeClass { myProp: KnockoutObservable<number>; constructor() { myProp = ko.observable(0); } }
Now, messing around with the console, when the class is initialized, the property returns 0 when called. However, after changing the input value, the property starts returning a string, eg. if I change it to 2, the return value is "2". This is obviously a problem when combining two such properties.
var x = myinstance.myProp() + myinstance.myProp();
The result is not 4, as you would expect, the result is "22", concatenation.
Is there a sane solution? Is this a knockout bug or documented behavior?
source share
You have bound a string value to a numeric type and are expecting automatic type conversion during binding. This won't work because, in the first place, KnockoutJS is a Javascript framework that doesn't know anything about the Typescript Type System.
You can either make the property a writable observable, or you can enter a read-only counter that simply triggers the current value of "myProp" via parseInt ().
source share