'Square brackets around vs after expression in Typescript
is there a difference between the following two square bracket notations in Typescript? Tried a couple of scenarios and it seems they are equivalent?
Thank you!
interface test {
a: string;
b: string;
}
const x: test[] = [{a: "aaaa", b: "bbbb"}]
const y: [test] = [{a: "aaaa", b: "bbbb"}]
Solution 1:[1]
As @VLAZ pointd out, x is an Array, while y is a Tuple.
The difference is observable even in this simple case.
interface test {
a: string;
b: string;
}
const x: test[] = [{a: "aaaa", b: "bbbb"}]
const y: [test] = [{a: "aaaa", b: "bbbb"}]
x.push({a: "a1", b: "b1"}); // works fine
y.push({a: "a1", b: "b1"}); // works fine
const a = x[1]; // works fine
const b = y[1]; // compilation error
// Tuple type '[test]' of length '1' has no element at index '1'.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lesiak |
