1

Within a class that derives from Array<T>, I have a splice override:

public splice(start?: number, deleteCount?: number, ...items: T[]): T[] {
    return super.splice(start, deleteCount, ...items);
}

Which compiles to...

SuperArray.prototype.splice = function (start, deleteCount) {
    var items = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        items[_i - 2] = arguments[_i];
    }

    return _super.prototype.splice.apply(this, [start, deleteCount].concat(items));
};

This doesn't work at all. It completely breaks splice! Is there something wrong with the way it compiles this .apply(this, [start, deleteCount].concat(items)) and how do I fix it?

What is happened with splice? Why it is broken?

array.splice(0); // array unaffected
4
  • 1
    What is happened with splice? Why it is broken? Commented Jan 11, 2017 at 22:24
  • @timocov see update Commented Jan 11, 2017 at 22:28
  • Behavior is the same typescriptlang.org/play/… Commented Jan 11, 2017 at 22:47
  • Your "super splice" frankly just wouldn't work as defined, it's totally ambiguous. Suppose you had a super array of numbers, how exactly is that function supposed to behave? Commented Jan 11, 2017 at 23:56

1 Answer 1

1

It seems that the reason this happens is that deleteCount is undefined, and if you try this:

let a = [1, 2, 3];
a.splice(0, undefined); // []
console.log(a); /// [1, 2, 3]

Exactly the same thing.
To get over this, you'll need to build the arguments array yourself, something like this:

class MyArray<T> extends Array<T> {
    public splice(start?: number, deleteCount?: number, ...items: T[]): T[] {
        if (start == undefined) {
            start = 0; // not sure here, but you wanted it to be optional
        }

        if (deleteCount == undefined) {
            deleteCount = this.length - start; // the default
        }

        const args = ([start, deleteCount] as any[]).concat(items);
        return super.splice.apply(this, args);
    }
}

Or something like:

public splice(start?: number, deleteCount?: number, ...items: T[]): T[] {
    if (deleteCount != undefined) {
        return super.splice(start, deleteCount, ...items);
    } else {
        return super.splice(start, ...items);
    }
}

But I haven't tested this one.

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

Comments

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.