Greg Gum Greg Gum - 1 month ago 7
TypeScript Question

How do I convert use of `arguments` in javascript in Typescript

I have an array. I want to add a method which is called whenever push is called on the array.

How do I write that in typescript?

I have tried:

addEvent(myArray) {
let _this = this;
myArray.push = function() {
Array.prototype.push.apply(myArray, arguments);

It give a compile time error: Supplied parameters do not match any signature of call target Expected 0, invoked with two.

I don't understand what it is saying.


Instead of using arguments, a more TS approach (and a better ES2015 approach in general) is to use rest parameters. I'm not exactly sure what you are trying to do, but you can use rest parameters like this:

addEvent(myArray) {
   // use an arrow function so you can avoid creating _this
   myArray.push = (...args: any[]) => {
        Array.prototype.push.apply(myArray, args);

Then you can call addEvent like this:

let arrayLikeObject = new SomeObjecct();

arrayLikeObject.push(1, 2, 3);

But, there's something not quite right about this approach. With TS, you should be providing stricter type annotations on your parameters. What type is myArray? What type of args does it accept? This should be explicitly spelled out. If it turns out that it accepts a wide variety of types, then that would indicate poor design as well.


Now that I know what you are trying to do, I can see that the function declaration should look more like this:

    (myArray as any[]).push = (...args: any[]): number => {
        Array.prototype.push.apply(myArray, args);
        return myArray.length;