string []和[string]之间的区别

Gie*_*pen 13 types typescript

请考虑以下Typescript示例.第一行导致错误'type undefined []不能分配给[string]'类型.最后两行确实编译.

let givesAnError: [string] = [];
let isOK: string[] = [];
let isAlsoOK: [string] = ["foo"];
Run Code Online (Sandbox Code Playgroud)

你如何解释[string]Typescript中的类型定义?

Nit*_*mer 16

first(givesAnError)和last(isAlsoOK)是元组,第二个(isOK)是数组.

对于数组,所有元素都是相同的类型:

let a: string[];
let b: boolean[];
let c: any[];
Run Code Online (Sandbox Code Playgroud)

但是对于元组,你可以有不同的类型(和固定长度):

let a: [string, boolean, number];
let b: [any, any, string];
Run Code Online (Sandbox Code Playgroud)

所以:

a = ["str1", true, 4]; // fine
b = [true, 3, "str"]; // fine
Run Code Online (Sandbox Code Playgroud)

但:

a = [4, true, 3]; // not fine as the first element is not a string
b = [true, 3]; // not fine because b has only two elements instead of 3
Run Code Online (Sandbox Code Playgroud)

重要的是要理解javascript输出将始终使用数组,因为在js中没有tuple这样的东西.
但是对于编译时间来说它很有用.

  • 所以 [string] 只是一个内部有 1 个字符串的数组,其中 string[] 是一个长度为 n 的字符串数组 (2认同)

Jas*_*ing 10

直接说吧

string[] // n-length array, must only contain strings

[string] // must be 1-length array, first element must be a string
Run Code Online (Sandbox Code Playgroud)