Questions:
- Is the behavior I'm observing the expected behavior for TypeScript?
- Is the behavior I'm observing the expected behavior for ECMAScript 6?
- Is there an easy way to walk back through the inheritance hierarchy to process the 'myStatic' array for each level? How do I know when to stop?
Description: When using TypeScript, there appears to be some interesting behavior with derived classes and static properties.
class MyBase {
static myStatic = [];
}
class MyDerived extends MyBase {}
MyBase.myStatic = ['one', 'two', 'three']
class MyDerived2 extends MyBase {}
document.body.innerHTML += "<b>MyDerived.myStatic:</b> " + JSON.stringify(MyDerived.myStatic) + "<br/>";
document.body.innerHTML += "<b>MyDerived2.myStatic:</b> " + JSON.stringify(MyDerived2.myStatic) + "<br/>";
This is the result:
MyDerived.myStatic: []
MyDerived2.myStatic: ["one","two","three"]
Edit: Adding example that illustrates different behavior between TypeScript and ECMA Script 6. Note: ECMA Script doesn't support static properties, so these examples use static methods.
TypeScript Code:
class MyBase {
static myStatic() { return []; }
}
class MyDerived extends MyBase {}
MyBase.myStatic = () => { return ['one', 'two', 'three']; }
class MyDerived2 extends MyBase {}
document.body.innerHTML += "<b>MyDerived.myStatic:</b> " + JSON.stringify(MyDerived.myStatic()) + "<br/>";
document.body.innerHTML += "<b>MyDerived2.myStatic:</b> " + JSON.stringify(MyDerived2.myStatic()) + "<br/>";
TypeScript Results:
MyDerived.myStatic: []
MyDerived2.myStatic: ["one","two","three"]
ECMA Script 6 Code: ES6 Fiddle
class MyBase {
static myStatic() { return []; }
}
class MyDerived extends MyBase {}
MyBase.myStatic = () => { return ['one', 'two', 'three']; };
class MyDerived2 extends MyBase {}
console.log("MyDerived.myStatic: " + JSON.stringify(MyDerived.myStatic()));
console.log("MyDerived2.myStatic: " + JSON.stringify(MyDerived2.myStatic()));
ECMA Script 6 Results
MyDerived.myStatic: ["one","two","three"]
MyDerived2.myStatic: ["one","two","three"]