1

The code is as below:

class BaseClass {
   propertyA: KnockoutObservable<string> = ko.observable<string>();
   constructor(message: string) {
      this.propertyA.subscribe((newValue)=>{
          console.log(newValue); // not run when change propertyA in ChildClassA instance.
      });
   }      
}
class ChildClassA extends BaseClass   {
   propertyA: KnockoutObservable<string> = ko.observable<string>(); //remove it, the issue is solved.
}

I noticed that when the ChildClassA has the same property named as the BaseClass, the subscription function for propertyA will not run. Remove that line of declaration in ChildClassA will solved the issue.

Why?

1 Answer 1

3

This is because you are reassigning this.propertyA in ChildClassA after assigning it in the BaseClass

When compiled to Javascript the code becomes

var BaseClass = (function () {
    function BaseClass(message) {
        this.propertyA = ko.observable();
        this.propertyA.subscribe(function (newValue) {
            console.log(newValue); // not run when change propertyA in ChildClassA instance.
        });
    }
    return BaseClass;
}());
var ChildClassA = (function (_super) {
    __extends(ChildClassA, _super);
    function ChildClassA() {
        _super.apply(this, arguments);
        this.propertyA = ko.observable(); //remove it, the issue is solved.
    }
    return ChildClassA;
}(BaseClass));

See it in playground

When instantiating ChildClassA you are calling super which calls the constructor of BaseClass which assigns this.propertyA and subscribes the listener. Fine. However right after the call to super, you are reassigning this.propertyA in ChildClassA constructor with the line

this.propertyA = ko.observable(); //remove it, the issue is solved.

Property initializations are moved to the constructor, after super calls.

There is no such thing as overriding properties (by inheritance) in Typescript.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.