Questions:
- Is the behavior that I am observing the expected behavior for TypeScript?
- Is the behavior that I am observing the expected behavior for ECMAScript 6?
- Is there an easy way to go through the inheritance hierarchy to process the "myStatic" array for each level? How to find out when to stop?
Description: When using TypeScript, there seems to be an interesting behavior with derived classes and static properties.
TypeScript Example
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: Add an example that illustrates the different behavior between TypeScript and ECMA Script 6. Note: ECMA Script does not 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 : 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
MyDerived.myStatic: ["one","two","three"]
MyDerived2.myStatic: ["one","two","three"]