3

I am trying to add some extension methods for a 2 dimensional array using typescript.

For a 1 dimensional Array the syntax is easy: e.g.

interface Array<T> {
    randomize();  
}
Array.prototype.randomize = function () {
    this.sort(() => (Math.round(Math.random()) - 0.5));
}

I was hoping I could do something similar with a 2 dimensional array, but the following does not work:

interface Array<Array<T>> {
    test();
}

Is it possible in Typescript to prototye on a 2 dimensional array?

1 Answer 1

1

There isn't any type system mechanism for this. Fundamentally, at runtime, Array.prototype either has a randomize function or it doesn't. You could write a standalone function that had a constraint, though:

function flatten<T extends Array<any>>(arr: T[]): T {
    return null; // TODO implement
}

var x: string[][] = /* ... */;
var y = flatten(x); // y: string[]
var z = flatten(y); // error

As an aside, you should not use that randomize function in earnest. Many sorting algorithms depend on transitivity of ordering (A > B, B > C implies A > C) or stability (A > B implies A > B), which your function does not preserve. This is at best going to be non-uniform and at worst might crash some runtimes.

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

2 Comments

not sure I understand "at runtime Array.prototype either has a randomize or it doesn't". The following javascript code works to add the extension method to Array: Array.prototype.randomize = function () { this.sort(function () { return (Math.round(Math.random()) - 0.5); }); }; My issue is that I am unable to do something similar for the 2 dimensional case (using typescript). I am definitely able to use my randomize extension method in the 1d case. NOTE: thanks for comment on randomize, actually this was just a lame example not the focus, I should just have called the method test().
Actally I should add that in Visual studio 2013 in my typeiscript for the 1D case, I see the warning "Extending prototype of native object "Array" may have unexpected side effects", not sure what these side effects may be...

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.