TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Declaring a subclass before its superclass passes compilation but causes runtime error

Open gilboa23 opened this issue 10 years ago • 2 comments

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.

gilboa23 avatar May 30 '16 11:05 gilboa23

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:

basarat avatar May 31 '16 04:05 basarat

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.

Arnavion avatar Jun 01 '16 02:06 Arnavion