Reputation: 15390
My Typescript file will compile with either of these declarations. Are they equivalent? Is there a name for these ways of declaring arrays?
interface Foo {
bounds: number[][];
bounds2: [[number, number], [number, number]];
}
The library into which I'm passing bounds
takes an array of two two-element arrays. bounds2
seems to express that more clearly above, but I'm not sure it's really doing the same thing.
Upvotes: 4
Views: 463
Reputation: 28656
I think the following code illustrates it quite nicely:
let a: number[][];
let b: [[number, number], [number, number]];
a = [5]; // error
a = [[5]]; // ok
a = [[5],[8,9,10]]; // ok
a = [[5],[8,9,10], [5]]; // ok
a = [[5, 'a']]; // error
b = [5]; // error
b = [[5]] // error
b = [[5,5]] // error
b = [[5,5], [5,5]] // ok
b = [[5,5], [5]] // error
b = [[5,5], [5,5,5]] // ok, a bit surprisingly
b = [[5,5,5], [5,5,5]] // ok, a bit surprisingly
b = [[5,5,5], [5,5,5], [5,5,5]] // ok, a bit surprisingly
b = [[5,5,5], [5,5,5], [5,5,5, 'a']] // error
b = [[5,5,5], [5,5,5], [5,5,5], [5,5,5,5,5,5]] // ok, a bit surprisingly
b = [[5,5,5]] // error
Upvotes: 1
Reputation: 5557
It's not the same thing.
bounds
represents an array of arrays of number
s.
bounds2
represents something that is called a tuple type, which is like a more detailed array description (with types on specified indexes). In this case this is a tuple containing two tuples, which both contain two number
s
Upvotes: 1