Reputation: 2245
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?
Upvotes: 3
Views: 1099
Reputation: 220954
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.
Upvotes: 1