2

Why does the following not work as expected:

class MyArray extends Array<number>
{
    constructor(n: number)
    {
        super(n);
    }
}

function initalize()
{
    var myArray = new MyArray(4);
    var l = myArray.length; // l should be 4
}

"l" turns out to be 0 instead of 4, which I expected. It doesn't make a difference whether I implement a constructor in "MyArray" or not.

1 Answer 1

1

Your code transpiles to

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 MyArray = (function (_super) {
    __extends(MyArray, _super);
    function MyArray(n) {
        _super.call(this, n);
    }
    return MyArray;
})(Array);
function initalize() {
    var myArray = new MyArray(4);
    var l = myArray.length; // l should be 4
}

And the problem is that you no longer deal with the original native type that has special properties. So your extended type - even if you would have succeeded - would be severely limited and confusing for others.

Details and gotchas can be found Axel Rauschmayer's article: http://www.2ality.com/2013/03/subclassing-builtins-es6.html

Sign up to request clarification or add additional context in comments.

4 Comments

I accept this as an answer, and it looks like there is no workaround. I would prefer Typescript would not allow such constructs, because they don't make sense.
@Gerhard Yes, Typescript is far from being a truly mature language, even though the syntax itself pretty much feels complete. Anyways, there is a workaround: an internal Array instance, and all of its methods replicated on your type, all of which only invoke the corresponding methods on the internal Array object.
@John that is what I tried, but did not succeed to implement an indexer to access array elements with myArray[i].
@Gerhard AFAIK, numeric indexers for Arrays are just numeric-like properties. You should be able to set the corresponding numeric-like property on your wrapper object when an element is added to the internal array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.