typescript 中的 String[] 和 [String] 有什么区别? 两者之间的最佳选择是什么?
最佳答案
它们不一样!
更新: 自 TypeScript 2.7这不再完全正确(请参阅下面的补充内容):
string[]
表示变量是一个字符串类型的数组(它可以是任何大小,甚至是空的)。[string]
表示变量是一个大小 >= 1 的数组,第一个条目是一个字符串- 从 2.7 开始:大小 === 1
[type]
语法可以扩展,例如[type1,type2,type3,typeN]
然后要求数组的大小至少为 N 并且前 N 个类型是指定的,而后面的类型是这些类型的联合。
一些不同的例子可以说明这个问题:
const testA: string[] = []; // good
const testB: [string] = []; // Error, array must have a string at position 0
const testC: [string, number] = ["a", 0]; // good
const testC1 = testC[0]; // testC1 is detected to be string
const testC2 = testC[1]; // testC2 is detected to be number
const testD: [string, number] = ["a", 0, "1"]; // good before 2.7, bad afterwards
const testD1 = testD[2]; // testD1 is detected to be string | number
const testE: [string, number] = ["a", 0, 1]; // good before 2.7, bad afterwards
const testE1 = testE[2]; // testE1 is detected to be string | number
const testF: [string, number] = ["a", 0, null]; // Error, null is not of type string|number
从 TypeScript 2.7 开始
The size is by default fixed .所以如果你想让 [string] 允许多个条目,你需要以一种非常丑陋的方式指定:
interface MinimumStrTuple extends Array<number | string> {
0: string;
}
关于javascript - typescript 中的 String[] 和 [String] 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982714/