Typescript中vs after表达式的方括号



在Typescript中以下两个方括号符号有区别吗?尝试了几个场景,它们似乎是相等的?

谢谢!

interface test {
a: string;
b: string;
}
const x: test[] = [{a: "aaaa", b: "bbbb"}]
const y: [test] = [{a: "aaaa", b: "bbbb"}]

正如@VLAZ指出的,x是一个数组,而y是一个元组。

即使在这个简单的例子中,差异也是可以观察到的。

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

最新更新