Skip to content

Static inheritance behavior is surprising #2082

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jvilk opened this issue Feb 19, 2015 · 2 comments
Closed

Static inheritance behavior is surprising #2082

jvilk opened this issue Feb 19, 2015 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@jvilk
Copy link

jvilk commented Feb 19, 2015

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.

class A {
    static bar: string = "foo";
}

A.bar = "Gotcha";

class B extends A {
}

console.log(B.bar); // prints 'Gotcha'

Is this desired behavior?

@danquirk
Copy link
Member

See some previous discussions about this:

https://typescript.codeplex.com/workitem/2047
#613

@jvilk
Copy link
Author

jvilk commented Feb 20, 2015

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.

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Mar 24, 2015
@mhegazy mhegazy closed this as completed Mar 24, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants