javascript - typescript 中的 String[] 和 [String] 有什么区别?

标签 javascript arrays typescript

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/

相关文章:

javascript - 我怎样才能让我的脚本在 div 中居中 img

javascript - react : 'this.state' of parent component is undefined inside a child component function

javascript - 根据驻留在 Json 数组中的对象的 Json 值获取 Json 键

c - (int) 转换如何作用于 char 数组和 char *?

arrays - 评估 for 循环中的条件时 Julia 中的 UndefVarError

reactjs - 当将函数作为自定义钩子(Hook)的参数传递时,我应该使用内存还是回调?

angular - 测试 angular if else block 和 subscribe(response => {} block in jasmine

javascript - Mongoose 模式创建空数组字段

javascript - D3 调整linkText位置

javascript - Angular2中如何调用多个函数,让它们互相等待