Declaring a subclass before its superclass passes compilation but causes runtime error
TypeScript Version:
1.8.10
Code
// SubClass is declared before its SuperClass
class SubClass extends SuperClass {
}
class SuperClass {
}
generated code:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var SubClass = (function (_super) {
__extends(SubClass, _super);
function SubClass() {
_super.apply(this, arguments);
}
return SubClass;
}(SuperClass));
var SuperClass = (function () {
function SuperClass() {
}
return SuperClass;
}());
Expected behavior: The order of class declarations in TypeScript should not be important. As evidence, the above code passes compilation and thus should not cause runtime error
.
Actual behavior:
Runtime error is thrown Uncaught TypeError: Cannot read property 'prototype' of undefined on line 4.
The reason is that in the call to __extends(SubClass, _super) on line 7 the _super variable is undefined, but the __extends function checks for strict null (b === null on line 4) and thus fails on undefined.
superclass passes compilation but causes runtime error
A fairly common error https://basarat.gitbooks.io/typescript/content/docs/tips/outFile.html
Similar to a user writing the following JavaScript:
console.log(foo.toString()); // Expecting it to work
var foo = 123;
Sadly you just have to be cautious about it for now. Of course it could be made an error (just isn't yet) :rose:
Duplicate of #6526 which was merged into #5207
Edit: Also
The order of class declarations in TypeScript should not be important. As evidence, the above code passes compilation and thus should not cause runtime error
is against ES semantics. The runtime behavior is correct. What's missing is the compile-time error.