You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I recently learned that TypeScript classes inherit static methods and fields, which really surprised me! Unlike object instances, static properties aren't set in a constructor, so their static initialization can't be re-run for subclasses. As a result, inherited static fields in subclasses will take on the current value of their parents' field as their initial value, which can be surprising.
classA{staticbar: string="foo";}A.bar="Gotcha";classBextendsA{}console.log(B.bar);// prints 'Gotcha'
Is this desired behavior?
The text was updated successfully, but these errors were encountered:
I see. From a discussion on esdicuss, it looks like B.__proto__ = A, and thus B would inherit bar from A.
In other words, accessing B.bar would initiate a prototype property lookup that is found on A. Further updates to A.bar would be reflected in a read of B.bar. However, that means that in ES6, assigning a value to B.bar would change the shape of B, since B itself does not have that property defined!
TypeScript does not emulate this behavior, as the __extend function redefines bar on B, causing the two fields to be completely distinct.
I have no proposal to remedy the situation if you desire to keep static field/method inheritance, since __proto__ is nonstandard and is not present in legacy browsers. So I recognize the difficulty in addressing the situation in a backwards-compatible manner without overly complicating runtime boilerplate.
I recently learned that TypeScript classes inherit static methods and fields, which really surprised me! Unlike object instances, static properties aren't set in a constructor, so their static initialization can't be re-run for subclasses. As a result, inherited static fields in subclasses will take on the current value of their parents' field as their initial value, which can be surprising.
Is this desired behavior?
The text was updated successfully, but these errors were encountered: