【问题标题】:Difference between string[] and [string]字符串 [] 和 [字符串] 之间的区别
【发布时间】:2017-01-29 13:10:15
【问题描述】:

考虑以下 Typescript 示例。第一行导致错误'type undefined[] is not assignable to type [string]'。最后两行编译。

let givesAnError: [string] = [];
let isOK: string[] = [];
let isAlsoOK: [string] = ["foo"];

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

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    第一个 (givesAnError) 和最后一个 (isAlsoOK) are tuples,第二个 (isOK) 是一个数组。

    使用数组,您的所有元素都属于同一类型:

    let a: string[];
    let b: boolean[];
    let c: any[];
    

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

    let a: [string, boolean, number];
    let b: [any, any, string];
    

    所以:

    a = ["str1", true, 4]; // fine
    b = [true, 3, "str"]; // fine
    

    但是:

    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
    

    了解 javascript 输出将始终使用数组非常重要,因为 js 中没有元组之类的东西。
    但是对于编译时间它是有用的。

    【讨论】:

    • so [string] 只是一个包含 1 个字符串的数组,其中 string[] 是一个长度为 n 的字符串数组
    • @JasonSebring Right
    【解决方案2】:

    直奔主题

    string[] // n-length array, must only contain strings
    
    [string] // must be 1-length array, first element must be a string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多