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"}]
2

1 Answer

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'.
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like