Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Extending Built-in JavaScript Types in TypeScript

Tech Jun 27 2

When subclassing native JavaScript constructors like Error or Array in TypeScript, unexpected behavior can occur if the code is compiled to ES5. Consider the following TypeScript implementation:

class CustomFailure extends Error {
  constructor(errorMsg: string) {
    super(errorMsg);
    // Explicitly restore the prototype chain
    Object.setPrototypeOf(this, CustomFailure.prototype);
  }

  fetchDetails() {
    return 'Details: ' + this.message;
  }
}

Compiling this down to ES5 produces a heavily modified output to simulate class inheritance. The generated JavaScript relies on a helper function to establish the prototype chain and static property inheritance:

'use strict';
var __inherit = (this && this.__inherit) || (function () {
    var assignStatics = function (child, parent) {
        assignStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (child, parent) { child.__proto__ = parent; }) ||
            function (child, parent) { for (var key in parent) if (Object.prototype.hasOwnProperty.call(parent, key)) child[key] = parent[key]; };
        return assignStatics(child, parent);
    };
    return function (child, parent) {
        if (typeof parent !== 'function' && parent !== null)
            throw new TypeError('Super expression must be a constructor or null, not ' + typeof parent);
        // Inherit static members
        assignStatics(child, parent);
        function Temp() { this.constructor = child; }
        // Set up prototype chain: child.prototype.__proto__ = parent.prototype
        child.prototype = parent === null ? Object.create(parent) : (Temp.prototype = parent.prototype, new Temp());
    };
})();
var CustomFailure = /** @class */ (function (parentClass) {
    __inherit(CustomFailure, parentClass);
    function CustomFailure(errorMsg) {
        var instance = parentClass.call(this, errorMsg) || this;
        // Explicitly restore the prototype chain
        Object.setPrototypeOf(instance, CustomFailure.prototype);
        return instance;
    }
    CustomFailure.prototype.fetchDetails = function () {
        return 'Details: ' + this.message;
    }; 
    return CustomFailure;
}(Error));

The TypeScript compiler captures the return value of the super constructor call (var instance = parentClass.call(this, errorMsg) || this;) to implicitly substitute the this context. However, native objects such as Error and Array internally rely on ES6's new.target to correctly adjust their internal prototype structure. In an ES5 environment, new.target cannot be accurately simulated when invoking a constructor function, causing native constructors to return an object whose prototype points directly to the base native class rather than the derived subclass.

If the explicit Object.setPrototypeOf(instance, CustomFailure.prototype); adjustment is omitted, two critical issues arise:

  • Methods defined on the subclass become inaccessible. Calling fetchDetails() will result in a TypeError because the method is undefined on the misaligned prototype.
  • Instance checks fail. The expression new CustomFailure() instanceof CustomFailure evaluates to false, as the instance's prototype chain bypasses CustomFailure.prototype.

Because prototype properties on native ES5 constructors are non-configurable, the super call modifies the context but retains the base class prototype. Manually resetting the prototype immediately after super() resolves this discrepancy. Any class that further extends CustomFailure must also apply this manual prototype assignment. In runtime environments lacking Object.setPrototypeOf, assigning this.__proto__ serves as a viable alternative.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.